在 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 | 浏览器开始请求资源的时间。 |
domainLookupStart | DNS 查询开始的时间。 |
domainLookupEnd | DNS 查询结束的时间。 |
connectStart | TCP 连接开始的时间。 |
connectEnd | TCP 连接完成的时间(包括 TLS 连接)。 |
secureConnectionStart | 如果是 HTTPS,TLS 握手开始的时间(否则为 0)。 |
requestStart | 浏览器发送请求的时间。 |
responseStart | 服务器开始响应的时间。 |
responseEnd | 服务器响应完成的时间。 |
domInteractive | DOM 解析完成的时间。 |
domContentLoadedEventStart | DOMContentLoaded 事件触发的时间。 |
domContentLoadedEventEnd | DOMContentLoaded 事件处理完成的时间。 |
domComplete | HTML 文档解析完成,所有资源加载完毕的时间。 |
loadEventStart | load 事件触发的时间。 |
loadEventEnd | load 事件处理完成的时间。 |
示例代码
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更精确和全面。