3

我正在尝试获取加载页面所需的时间,但我不确定运行此脚本的正确方法。

我以为我可以这样做:

window.addEventListener("load", function(){
    console.log(performance.getEntriesByType("navigation")[0].duration);
});

但是它总是返回 0;

如果我之后在控制台中运行它,它工作正常。在窗口加载事件之后我可以使用另一个事件吗?这个函数的正确用法是什么?

编辑:似乎使用 setTimeout 将其添加为页面完全加载后运行的第一件事。工作代码是:

window.addEventListener("load", function(){    
    setTimeout(function(){
        console.log(performance.getEntriesByType("navigation")[0].duration);
    }, 0);
});
4

2 回答 2

0

您可以使用浏览器提供的性能 API 来获取加载时间

 let loadTime = window.performace.timing.loadEventEnd - window.performance.timing.navigationStart;

结帐https://developer.mozilla.org/en-US/docs/Web/API/Navigation_timing_API了解更多

于 2021-11-26T13:57:13.580 回答
0

您还可以轮询正在设置的值:

const perf = () => {
  const duration = performance.getEntriesByType("navigation")[0].duration;
  if (!duration) setTimeout(perf, 0);
  else console.log({ duration });
}
window.addEventListener('DOMContentLoaded', perf);
于 2021-11-26T14:01:07.320 回答