Page load time with JavaScript

andrei picture andrei · Oct 24, 2012 · Viewed 22.8k times · Source

I am looking for a proper way to test the time it takes a page to fully load all its resources. What I've done so far is add:

window.startTime = (new Date).getTime(); // after the title in my page

And

window.onload = function () {
    console.log((new Date).getTime() - window.startTime);
}
window.addEventListener('load',function () {
    console.log((new Date).getTime() - window.startTime);   
},false);

Way down in the footer. Is this a good way to measure? Could there be differences between load time and perceived load time? From what I'm seeing the events trigger after all the resources have loaded including images. Are there any differences between the two events? Also can I use PageSpeed to test this? (I know I can do it in chrome dev tools, but I also want a script so that I can keep track of data.)

Answer

jAndy picture jAndy · Oct 24, 2012

It is pretty much the only way in legacy browsers to measure times. But for the rescue, most browsers do implement the window.performance object which offers a very, very accurate way of getting times.

A typical window.performance.timing output:

connectEnd 1351036536696
connectStart 1351036536696
domComplete 1351036538277
domContentLoadedEventEnd 1351036538146
domContentLoadedEventStart 1351036538119
domInteractive 1351036538042
domLoading 1351036537552
domainLookupEnd 1351036536694
domainLookupStart 1351036536694
fetchStart 1351036536696
loadEventEnd 1351036538295
loadEventStart 1351036538277
navigationStart 1351036536696

..which is not even the full list.