直接用performance.getentriesbytype("navigation")[0]获取导航时序即可精准计算各阶段耗时,关键在于校验字段有效性并拆解重定向、dns、tcp、ssl等环节:重定向耗时需确认redirectstart>0后再计算redirectend-redirectstart;tcp耗时为connectend-connectstart,ssl耗时为connectend-secureconnectionstart(仅当secureconnectionstart>0);dns耗时为domainlookupend-domainlookupstart,均须排除0值干扰。

直接用 performance.getEntriesByType("navigation")[0] 获取导航时序,就能准确算出重定向和网络连接各阶段耗时——关键不是看总时间,而是拆解每一步卡在哪。
重定向耗时:先确认有没有,再看卡在哪
重定向不是“有或无”的问题,而是“几次、哪次慢”。浏览器只记录同源重定向链,跨域跳转会中断计时。
-
判断是否存在重定向:检查
nav.redirectStart > 0,若为 0 则本次无重定向 -
计算总重定向耗时:
nav.redirectEnd - nav.redirectStart,注意这个值包含所有中间跳转的 DNS、TCP、请求响应总和 -
定位瓶颈环节:若耗时明显偏高(如 >500ms),需结合 Resource Timing 查看每次跳转对应的资源条目,重点看
responseEnd - requestStart(服务端响应)和connectEnd - connectStart(新域名建连)
TCP 连接与 SSL 协商:区分是否复用连接
TCP 和 SSL 耗时受连接复用影响极大。同一域名下连续请求可能复用连接,但重定向后新域名大概率要重连。
-
TCP 建连耗时:
nav.connectEnd - nav.connectStart,若等于 0,说明用了 HTTP/2 复用或本地缓存连接 -
SSL 协商耗时(HTTPS):仅当
nav.secureConnectionStart > 0时有效,计算为nav.connectEnd - nav.secureConnectionStart -
注意陷阱:Safari 和多数 WebView 中
connectStart/connectEnd常为 0,此时应 fallback 到 Resource Timing 中对应资源的字段,比如第三方脚本的connectEnd - connectStart
DNS 查询:别只看平均值,关注首次与后续差异
DNS 耗时波动大,尤其在移动弱网下。单次查询快不代表稳定,要观察首次解析与后续复用的差距。
-
首屏 DNS 耗时:
nav.domainLookupEnd - nav.domainLookupStart,反映主域名解析延迟 -
对比资源 DNS:用
performance.getEntriesByType("resource")筛出关键第三方脚本,取其domainLookupEnd - domainLookupStart,若显著高于主域名,说明该 CDN 或服务商 DNS 响应慢 -
优化提示:DNS 预解析(
<link rel="dns-prefetch" href="//cdn.example.com">)对首次访问有效,但对重定向链中动态生成的域名无效
实操建议:避开 timing API 兼容性坑
performance.timing 已废弃,在 Safari 和主流 WebView 中不可靠,必须用现代接口。
-
首选方案:始终使用
performance.getEntriesByType("navigation")[0],字段语义清晰、精度高、全平台支持 -
安全 fallback:若返回空数组(如页面未完成加载),可监听
window.addEventListener("load", ...)后再执行;极端情况用performance.navigationStart(非 timing.navigationStart)配合Date.now()估算 -
验证有效性:计算前先检查关键字段是否为正数,例如
nav.responseStart > 0 && nav.domainLookupStart > 0,避免 NaN 或负值干扰分析
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











