Using jQuery to Get Page Load Time

If you ever find yourself needing to know how long it takes for one of your pages to load, we've got the snippet for you. There are many reasons you might want to understand how long a page load takes -- doing this might especially appeal to developers who have got their pages loaded with ads, and want to test how much they're slowing down the site. You can try loading the page yourself, but sometimes to the naked eye it can appear as if the page has loaded, when really scripts are still trying to be fetched and ads have yet to be loaded. Under these circumstances, it's easier to just test it out using code.

See below for the code snippet:

var start = new Date(); 
jQuery.ready(); 
var end = new Date(); 
var difference = (endTime - startTime) / 1000; 
alert("document.ready time: " + difference + " seconds");

In the code above, we first record the time (using the Date method) when the page is requested and begins to load. This line must go at the top of the code. Then, one the page is loaded (that's what the jQuery.ready() line is for) we fetch the time again. We find the difference between the two and divide the answer by 1000, because the time is measured in milliseconds and we want our answer to be in seconds for the purpose of this tutorial (but milliseconds is totally fine too if you'd rather your answer be in that format -- just remove the division part of the equation!) and set the time to the variable "difference". From there, we use an alert to let us know the time it took for the page to load by referencing the difference variable. If you don't want the time difference to appear as an alert, you can log it to the Console or add it to your HTML -- whichever works best for you and your project.



Responsive Menu
Add more content here...