如何使用“ performancenavigation” API获取页面加载时间?
I am trying to to use the PerformanceNavigationTiming
API 生成页面加载度量。
上面链接的MDN API文档说performanceNtry.duration
应该给我我需要的东西,因为它:
[r] Eturn是一个时间戳,这是performancenAvigationTiming.loadeventend和performanceNtry.starttime属性之间的差异。
但是,当我检查此属性时,我只会得到0
。 这样检查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)
}
}, [])
}
我正在从运行使用
函数的React Hook中访问此API,该功能等待window
加载事件,然后像 ,我还在“性能条目”上调用tojson
,实际上表明持续时间
的值>)都是0
也:
有人知道为什么我会得到这个值吗?
I am trying to to use the PerformanceNavigationTiming
API to generate a page load metric.
The MDN API document linked above says that the PerformanceEntry.duration
should give me what I need because it:
[r]eturns a timestamp that is the difference between the PerformanceNavigationTiming.loadEventEnd and PerformanceEntry.startTime properties.
However, when I check this property, I get simply 0
. I'm accessing this API from within a React hook that runs a useEffect
function that wait for the window
load event and then checks the api like so:
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)
}
}, [])
}
As you can see there, I also call toJSON
on the performance entry and indeed it shows that the values upon which duration
(startTime
and loadEventEnd
) are both 0
as well:
Does anyone know why I am getting this value?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我终于能够使用与事件侦听器不同的方法使它工作。当
load
事件触发时,数据应该准备就绪是合乎逻辑的,但是我获得数据的唯一方法是使用性能API的另一个功能:performance observer < /code>,当新数据可用时会发出回调。
这是对我有用的代码:
I was finally able to get this to work using a different method than the event listener. It certainly is logical that the data should be ready when the
load
event fires, but the only way I was able to get the data was to use another feature of the Performance API: thePerformanceObserver
, which fires a callback when a new piece of data has become available.Here is the code that worked for me: