Get page load time in react by PerformanceNavigationTiming

3.1k Views Asked by At

I used to get page load time in my react project by window.performance.timing but I found that This property is deprecated. so I tried to get load time by PerformanceNavigationTiming. This is the code:

window.addEventListener("load", function() {
    const page_load_time = performance.getEntriesByType("navigation")[0];
    console.log(page_load_time);
    console.log(`${page_load_time.loadEventEnd}`);
});

console.log(page_load_time); give me an object that contains loadEventEnd number in ms but console.log(${page_load_time.loadEventEnd}); gives me zero

  1. Why zero?
  2. Is this the right way to get page load time?
1

There are 1 best solutions below

0
Dylan Barber On

TSX Way:

const perf = window.performance.getEntriesByType("navigation")[0];
const loadTime: number =
        (perf as PerformanceNavigationTiming).loadEventEnd -
        (perf as PerformanceNavigationTiming).requestStart;

JSX Way:

const perf = window.performance.getEntiresByType("navigation")[0];
const loadTime = perf.loadEventEnd - perf.requestStart;

Make sure to wrap this in a setTimeout(() => {}, 0) so the onLoad event completes first and gives accurate timing