我正在尝试使用 PerformanceNavigationTiming
API生成页面加载指标。
上面链接的 MDN API 文档说 PerformanceEntry.duration
应该给我我需要的东西,因为它:
[r]eturns a timestamp that is the difference between the PerformanceNavigationTiming.loadEventEnd and PerformanceEntry.startTime properties.
但是,当我检查此属性时,我只得到 0
。我从一个 React 钩子(Hook)中访问此 API,该钩子(Hook)运行一个 useEffect
函数,该函数等待 window
加载事件,然后检查 API,如下所示:
export const useReportPageLoadTime = () => {
useEffect(() => {
const reportTime = () => {
let navPerformance: PerformanceEntry
navPerformance = window.performance.getEntriesByType('navigation')[0]
console.log({
duration: navPerformance.duration,
blob: navPerformance.toJSON()
})
}
if (document.readyState === 'complete') {
reportTime()
return null
} else {
window.addEventListener('load', reportTime)
return () => window.removeEventListener('load', reportTime)
}
}, [])
}
正如您所看到的,我还在性能条目上调用了 toJSON
,实际上它显示了 duration
(startTime
和 loadEventEnd
)也都是 0
:
有谁知道为什么我会得到这个值?
最佳答案
我终于能够使用与事件监听器不同的方法来使其工作。当 load
事件触发时,数据应该准备就绪,这当然是合乎逻辑的,但我获取数据的唯一方法是使用 Performance API 的另一个功能:PerformanceObserver
,当新数据可用时会触发回调。
这是对我有用的代码:
export const useReportPageLoadMetrics = () => {
useEffect(() => {
const perfObserver = new PerformanceObserver((observedEntries) => {
const entry: PerformanceEntry =
observedEntries.getEntriesByType('navigation')[0]
console.log('pageload time: ', entry.duration)
})
perfObserver.observe({
type: 'navigation',
buffered: true
})
}, [])
}
关于javascript - 如何使用 `PerformanceNavigationTiming` API获取页面加载时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72907673/