全面掌握JavaScript页面导航性能分析:PerformanceNavigationTiming详解与实战

204 阅读2分钟

在 JavaScript 中,window.performance.getEntriesByType('navigation')[0] 用于获取当前页面的 导航性能信息,它返回 PerformanceNavigationTiming 对象,其中包含了关于页面加载的详细时间数据。


语法

const navigationEntry = window.performance.getEntriesByType('navigation')[0];

返回值

  • navigationEntry 是一个 PerformanceNavigationTiming 对象,包含了页面导航的各个时间点的详细数据。

PerformanceNavigationTiming 详细属性

以下是 PerformanceNavigationTiming 可能包含的重要属性:

属性说明
type导航类型,可能的值:navigate(正常导航)reload(刷新)back_forward(前进/后退)prerender(预渲染)
startTime记录导航开始的时间点(一般为 0)。
redirectCount该导航过程中发生的重定向次数。
redirectStart重定向开始时间(如果没有重定向,则为 0)。
redirectEnd重定向结束时间(如果没有重定向,则为 0)。
fetchStart浏览器开始请求资源的时间。
domainLookupStartDNS 查询开始的时间。
domainLookupEndDNS 查询结束的时间。
connectStartTCP 连接开始的时间。
connectEndTCP 连接完成的时间(包括 TLS 连接)。
secureConnectionStart如果是 HTTPS,TLS 握手开始的时间(否则为 0)。
requestStart浏览器发送请求的时间。
responseStart服务器开始响应的时间。
responseEnd服务器响应完成的时间。
domInteractiveDOM 解析完成的时间。
domContentLoadedEventStartDOMContentLoaded 事件触发的时间。
domContentLoadedEventEndDOMContentLoaded 事件处理完成的时间。
domCompleteHTML 文档解析完成,所有资源加载完毕的时间。
loadEventStartload 事件触发的时间。
loadEventEndload 事件处理完成的时间。

示例代码

const navigationEntry = window.performance.getEntriesByType('navigation')[0];

console.log("导航类型:", navigationEntry.type);
console.log("重定向次数:", navigationEntry.redirectCount);
console.log("DNS 查询时间:", navigationEntry.domainLookupEnd - navigationEntry.domainLookupStart, "ms");
console.log("TCP 连接时间:", navigationEntry.connectEnd - navigationEntry.connectStart, "ms");
console.log("请求响应时间:", navigationEntry.responseEnd - navigationEntry.requestStart, "ms");
console.log("DOM 解析时间:", navigationEntry.domInteractive - navigationEntry.responseEnd, "ms");
console.log("页面加载完成时间:", navigationEntry.loadEventEnd - navigationEntry.startTime, "ms");

performance.timing 的区别

过去,开发者主要使用 performance.timing已废弃),但现在推荐使用 getEntriesByType('navigation') 获取更详细和精准的性能数据。

API状态适用性
performance.timing已废弃适用于老浏览器,但精度较低
performance.getEntriesByType('navigation')推荐适用于现代浏览器,精度更高

兼容性

getEntriesByType('navigation') 适用于现代浏览器,如: ✅ Chrome 58+
✅ Firefox 57+
✅ Edge 79+
✅ Safari 11+
❌ Internet Explorer(不支持)

如果需要在老旧浏览器(如 IE)中使用,可以回退到 performance.timing


总结

  • window.performance.getEntriesByType('navigation')[0] 返回 PerformanceNavigationTiming 对象,包含详细的页面加载时间信息。
  • 通过这个对象,可以分析 DNS 查询、TCP 连接、服务器响应、DOM 解析、页面加载等各个阶段的耗时情况。
  • 现代浏览器推荐使用,比 performance.timing 更精确和全面。