javascript - 如何使用 `PerformanceNavigationTiming` API获取页面加载时间?

标签 javascript performance

我正在尝试使用 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 (startTimeloadEventEnd)也都是 0:

picture of data

有谁知道为什么我会得到这个值?

最佳答案

我终于能够使用与事件监听器不同的方法来使其工作。当 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/

相关文章:

javascript - 有没有办法将 javascript 对象视为 JSON?

ruby - 我可以使这个 Ruby 代码更快和/或使用更少的内存吗?

javascript - 映射时嵌套数据表

javascript - Node.js Stream Transform 是否维护 block 的顺序?

javascript - 单击 Ext.menu.Menu 中的菜单项

c# - String.Replace(char, char) 还是 Replace(string, string)?

java - 优化代码以找到给定数字 N 的阶乘的个位数

JavaScript 通过滚动添加一次类

java - 异步日志

performance - 避免 Numpy Index For 循环