Navigation Timing API 提供了高精度时间戳,用于度量当前页面加载速度。浏览器会在导航事件发生时自动记录PerformanceNavigationTiming 条目。这个对象会捕获大量时间戳,用于描述页面是
何时以及如何加载的。
下面的例子计算了loadEventStart 和loadEventEnd 时间戳之间的差:
const [performanceNavigationTimingEntry] = performance.getEntriesByType(‘navigation’);
console.log(performanceNavigationTimingEntry);
// PerformanceNavigationTiming {
// connectEnd: 2.259999979287386
// connectStart: 2.259999979287386
// decodedBodySize: 122314
// domComplete: 631.9899999652989
// domContentLoadedEventEnd: 300.92499998863786
// domContentLoadedEventStart: 298.8950000144541
// domInteractive: 298.88499999651685
// domainLookupEnd: 2.259999979287386
// domainLookupStart: 2.259999979287386
// duration: 632.819999998901
// encodedBodySize: 21107
// entryType: “navigation”
// fetchStart: 2.259999979287386
// initiatorType: “navigation”
// loadEventEnd: 632.819999998901
// loadEventStart: 632.0149999810383
// name: " https://foo.com "
// nextHopProtocol: “h2”
// redirectCount: 0
// redirectEnd: 0
// redirectStart: 0
// requestStart: 7.7099999762140214
// responseEnd: 130.50999998813495
// responseStart: 127.16999999247491
// secureConnectionStart: 0
// serverTiming: []
// startTime: 0
// transferSize: 21806
// type: “navigate”
// unloadEventEnd: 132.73999997181818
// unloadEventStart: 132.41999997990206
// workerStart: 0
// }
console.log(performanceNavigationTimingEntry.loadEventEnd –
performanceNavigationTimingEntry.loadEventStart);
// 0.805000017862767
Resource Timing API
Resource Timing API 提供了高精度时间戳,用于度量当前页面加载时请求资源的速度。浏览器会在
加载资源时自动记录PerformanceResourceTiming。这个对象会捕获大量时间戳,用于描述资源加
载的速度。
下面的例子计算了加载一个特定资源所花的时间:
const performanceResourceTimingEntry = performance.getEntriesByType(‘resource’)[0];
console.log(performanceResourceTimingEntry);
// PerformanceResourceTiming {
// connectEnd: 138.11499997973442
// connectStart: 138.11499997973442
// decodedBodySize: 33808
// domainLookupEnd: 138.11499997973442
// domainLookupStart: 138.11499997973442
// duration: 0
// encodedBodySize: 33808
// entryType: “resource”
// fetchStart: 138.11499997973442
// initiatorType: “link”
// name: “https://static.foo.com/bar.png”,
// nextHopProtocol: “h2”
// redirectEnd: 0
// redirectStart: 0
// requestStart: 138.11499997973442
// responseEnd: 138.11499997973442
// responseStart: 138.11499997973442
// secureConnectionStart: 0
// serverTiming: []
// startTime: 138.11499997973442
// transferSize: 0
// workerStart: 0
// }
console.log(performanceResourceTimingEntry.responseEnd –
performanceResourceTimingEntry.requestStart);
// 493.9600000507198
通过计算并分析不同时间的差,可以更全面地审视浏览器加载页面的过程,发现可能存在的性能瓶颈。
javascript基础学习系列五百八十一:Navigation Timing API
最新推荐文章于 2024-06-26 09:39:13 发布