javascripthtmlperformanceeventsnavigation-timing-api

How to get page load duration using JavaScript


I am trying to get the time it takes to load a page and I am not sure of the correct way to run this script.

I thought I could do this:

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

However it always returns 0;

If I run it in the console after, it works fine. Is there another event I can use that runs after the window load event? What is the correct usage of this function?

EDIT: It seems using setTimeout adds it as the first thing that runs after the page has completely loaded. Working code is:

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

Solution

  • You can also poll for the value being set:

    const perf = () => {
      const duration = performance.getEntriesByType("navigation")[0].duration;
      if (!duration) setTimeout(perf, 0);
      else console.log({ duration });
    }
    window.addEventListener('DOMContentLoaded', perf);