如何使用 Navigation Timing API 获取 TTFB 并断言 <200 ms?
解读
面试官想通过这道题同时考察三件事:
- 你是否知道 Navigation Timing API 是浏览器原生的性能数据接口,而不是 Selenium 自带的方法;
- 你是否能在 Selenium 里正确注入 JavaScript 并拿到
performance.timing或performance.getEntriesByType('navigation')[0]中的 TTFB(Time to First Byte); - 你是否会把拿到的 毫秒值 用断言库(TestNG/JUnit/Pytest 等)做 <200 ms 的判定,并考虑国内网络环境下的 容错策略。
国内大厂面试中,这道题常作为“自动化+性能”交叉题出现,答得太浅会被追问“白屏时间怎么算”,答得太深又容易过度设计,因此要把 脚本稳定性、数据精度、重试机制 说清楚。
知识点
- Navigation Timing 二级规范 中
responseStart - fetchStart才是 官方 TTFB; - Selenium Java 用
JavascriptExecutor.executeScript返回Number,Python 用driver.execute_script返回float; - 国内 Chrome 98+ 已默认启用 PerformanceNavigationTiming 新对象,老接口
performance.timing将被废弃,需做 向下兼容; - 断言库选择:Java 体系用 TestNG Assert.assertTrue(ttfb < 200),Python 体系用 pytest.assert(ttfb < 200);
- 面试加分项:
- 先 wait until
responseStart > 0再取值,避免空值; - 连续采样 3 次去掉异常值再平均,降低 GFW/CDN 抖动带来的误判;
- 把阈值做成 Maven/Gradle 或 Pytest ini 参数,方便 多环境复用。
- 先 wait until
答案
以 Selenium + Java + TestNG 为例,给出可直接落地的脚本:
@Test
public void ttfbShouldBeLessThan200ms() {
WebDriver driver = new ChromeDriver(); // 国内镜像源已配置
driver.get("https://www.example.com"); // 被测站点
// 1. 等待页面完成网络活动,避免取到 0
new WebDriverWait(driver, Duration.ofSeconds(5))
.until(webDriver -> (Boolean) ((JavascriptExecutor) webDriver)
.executeScript("return performance.timing.responseStart > 0"));
// 2. 取 TTFB(单位 ms)
Long ttfb = (Long) ((JavascriptExecutor) driver)
.executeScript("return performance.timing.responseStart - performance.timing.fetchStart;");
// 3. 断言
Assert.assertTrue(ttfb < 200, "TTFB 实际值:" + ttfb + " ms,超过 200 ms 阈值");
driver.quit();
}
若浏览器为 Chrome 100+,推荐改用新 API,脚本更严谨:
Long ttfb = (Long) ((JavascriptExecutor) driver)
.executeScript(
"const nav = performance.getEntriesByType('navigation')[0];" +
"return Math.round(nav.responseStart - nav.fetchStart);");
拓展思考
- 跨浏览器兼容性:Firefox 55+、Edge 79+ 均支持新 API,但 IE11 只能回退到
performance.timing,面试时可主动提及 Capability 降级策略。 - 持续集成:在 Jenkins + Allure 报告里把 TTFB 作为 自定义指标 输出,趋势图一旦 >200 ms 就自动标红,可体现你对 DevOps 性能门禁的理解。
- 移动端场景:国内 微信小程序 Web-view 禁用了
performance.getEntriesByType,需要改用 Chrome DevTools Protocol(CDP) 的Network.responseReceived事件,Selenium 4 内置 DevTools::send 方法,可现场写一段command = "Network.enable"的代码展示深度。 - 面试反向提问:可以问面试官“200 ms 阈值是否已扣除 本地代理、公司网关 的延迟”,体现你对 真实用户可感知性能 的闭环思考。