Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get page load time in react by PerformanceNavigationTiming

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?
like image 545
taha amiri Avatar asked Dec 07 '25 02:12

taha amiri


1 Answers

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

like image 199
Dylan Barber Avatar answered Dec 08 '25 14:12

Dylan Barber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!