[javascript] Calculating Page Load Time In JavaScript

I am trying to make a webpage that, when it starts loading, uses an Interval to start a timer.

When the page fully loads, it stops the timer,

but 99% of the time i get time measurements of 0.00 or 0.01 even if it takes longer.

Occasionally, it says something that makes more sense like .28 or 3.10 at some times.

Here is the code if it helps:

var hundredthstimer = 0;
var secondplace = 0;

function addinc(){

    hundredthstimer += 1;
    if (inctimer == 100){
        hundredthstimer = 0;
        secondplace += 1;
    }

}

var clockint = setInterval(addinc, 10);

function init(){
    var bconv1 = document.getElementById("bconverter1");
    var bconv2 = document.getElementById("bconverter2");

    $(bconv2).hide();

    clearInterval(clockint);

    if (inctimer.len !== 2){
        inctimer = "0" + inctimer;
    }
    alert(secondplace + "." + inctimer);
}
onload = init;

So it basically creates a variable called hundredthstimer which is increased by '1' every 10 miliseconds(.01 seconds).

Then, if this number reaches 1000(1 full second), a variable called secondsplace goes up by 1, since that is how many full seconds it has run for.

Then, it alerts secondsplace, a decimal point, and hundredthsplace as the total load time.

But the problem above with incorrect numbers still exists. Why?

This question is related to javascript load setinterval

The answer is


Why so complicated? When you can do:

var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart;

If you need more times check out the window.performance object:

console.log(window.performance);

Will show you the timing object:

connectEnd                 Time when server connection is finished.
connectStart               Time just before server connection begins.
domComplete                Time just before document readiness completes.
domContentLoadedEventEnd   Time after DOMContentLoaded event completes.
domContentLoadedEventStart Time just before DOMContentLoaded starts.
domInteractive             Time just before readiness set to interactive.
domLoading                 Time just before readiness set to loading.
domainLookupEnd            Time after domain name lookup.
domainLookupStart          Time just before domain name lookup.
fetchStart                 Time when the resource starts being fetched.
loadEventEnd               Time when the load event is complete.
loadEventStart             Time just before the load event is fired.
navigationStart            Time after the previous document begins unload.
redirectCount              Number of redirects since the last non-redirect.
redirectEnd                Time after last redirect response ends.
redirectStart              Time of fetch that initiated a redirect.
requestStart               Time just before a server request.
responseEnd                Time after the end of a response or connection.
responseStart              Time just before the start of a response.
timing                     Reference to a performance timing object.
navigation                 Reference to performance navigation object.
performance                Reference to performance object for a window.
type                       Type of the last non-redirect navigation event.
unloadEventEnd             Time after the previous document is unloaded.
unloadEventStart           Time just before the unload event is fired.

Browser Support

More Info


It is hard to make a good timing, because the performance.dominteractive is miscalulated (anyway an interesting link for timing developers).

When dom is parsed it still may load and execute deferred scripts. And inline scripts waiting for css (css blocking dom) has to be loaded also until DOMContentloaded. So it is not yet parsed?

And we have readystatechange event where we can look at readyState that unfortunately is missing "dom is parsed" that happens somewhere between "loaded" and "interactive".

Everything becomes problematic when even not the Timing API gives us a time when dom stoped parsing HTML and starting The End process. This standard say the first point has to be that "interactive" fires precisely after dom parsed! Both Chrome and FF has implemented it when document has finished loading sometime after it has parsed. They seem to (mis)interpret the standars as parsing continues beyond deferred scripts executed while people misinterpret DOMContentLoaded as something hapen before defered executing and not after. Anyway...

My recommendation for you is to read about? Navigation Timing API. Or go the easy way and choose a oneliner of these, or run all three and look in your browsers console ...

  document.addEventListener('readystatechange', function() { console.log("Fiered '" + document.readyState + "' after " + performance.now() + " ms"); });

  document.addEventListener('DOMContentLoaded', function() { console.log("Fiered DOMContentLoaded after " + performance.now() + " ms"); }, false);

  window.addEventListener('load', function() { console.log("Fiered load after " + performance.now() + " ms"); }, false);

The time is in milliseconds after document started. I have verified with Navigation? Timing API.

To get seconds for exampe from the time you did var ti = performance.now() you can do parseInt(performance.now() - ti) / 1000

Instead of that kind of performance.now() subtractions the code get little shorter by User Timing API where you set marks in your code and measure between marks.


The answer mentioned by @HaNdTriX is a great, but we are not sure if DOM is completely loaded in the below code:

var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart; 

This works perfectly when used with onload as:

window.onload = function () {
    var loadTime = window.performance.timing.domContentLoadedEventEnd-window.performance.timing.navigationStart; 
    console.log('Page load time is '+ loadTime);
}

Edit 1: Added some context to answer

Note: loadTime is in milliseconds, you can divide by 1000 to get seconds as mentioned by @nycynik


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to load

jQuery load first 3 elements, click "load more" to display next 5 elements Javascript: Load an Image from url and display Selenium wait until document is ready Calculating Page Load Time In JavaScript File loading by getClass().getResource() How do I load an url in iframe with Jquery Can I get JSON to load into an OrderedDict? changing source on html5 video tag Load content of a div on another page JavaScript load a page on button click

Examples related to setinterval

How to make `setInterval` behave more in sync, or how to use `setTimeout` instead? How can I pause setInterval() functions? Can clearInterval() be called inside setInterval()? Stop setInterval clearInterval() not working Calculating Page Load Time In JavaScript Javascript setInterval not working How to start and stop/pause setInterval? How do I reset the setInterval timer? jquery function setInterval