Measuring Site Load Times via performance api

Brad Herman picture Brad Herman · Sep 30, 2011 · Viewed 10.3k times · Source

I listened to a talk by Steve Souders a few days ago and he mentioned the new performance spec that newer browsers are implementing and it was pretty intriguing. In his speech he mentioned the following example as a means of measuring perceived page load time:

var timing = performance.timing;
var loadtime = timing.loadEventEnd - timing.navigationStart;
alert("Perceived time:"+loadtime);

Clearly this is a basic example, but when trying it on my development environment, I get crazy numbers like -1238981729837 as the answer because loadEventEnd is < 0.

Obviously something is amiss and there are many improvements that can be made to this example to give more information and produce a greater reliability. (I am aware this is only implemented in a few browsers).

So, what are some suggestions on how to use this api to track page load times via Javascript for analysis of my site performance?

Answer

Ionut Popa picture Ionut Popa · Jun 15, 2012

You need to measure the loadEventEnd after the onload event has finished or else it will be reported as 0, as never happened. (jquery example for attaching to the onload event)

$(window).load(function(){
 setTimeout(function(){
 window.performance = window.performance || window.mozPerformance || window.msPerformance || window.webkitPerformance || {};
 var timing = performance.timing || {};
 var parseTime = timing.loadEventEnd - timing.responseEnd;
 console.log('Parsetime: ', parseTime);
 }, 0);
});