PHASETWO

Blog

How to Defer Google Analytics Until After Page Load

I'm working on a project to super-optimize a web site. By super optimize, I mean to go way beyond the bounds of reason and get every last millisecond back I can.

If you have a web application that uses an onload listener you will no doubt have waited in agony for some 3rd party JavaScript include on your page to finish loading so your page can get on with some function or another. One of the more common JS includes must surely be Google Analytics which, while often pretty quick, can still lag sometimes.

So I decided to do a quick bit of experimenting to see if I could defer the Google Analytics include until after page load, and thus allow my onload code to run sooner. It turns out to be pretty simple actually. Here's my code:

var _googleInterval;
function addGoogleTracking()
{
	var sc = document.createElement('script');
	sc.type = 'text/javascript';
	sc.src = 'http://www.google-analytics.com/ga.js';
	document.getElementsByTagName("head").item(0).appendChild(sc);
	_googleInterval = setInterval(activateGoogle,250);
}
function activateGoogle()
{
	if(typeof _gat != 'undefined') 
	{
		clearInterval(_googleInterval);
		var pageTracker = _gat._getTracker("YOUR-TRACKING-ID-HERE");
		pageTracker._initData();
		pageTracker._trackPageview();
	}
}

Obviously you need to call addGoogleTracking() in your onload function. In a nutshell we're adding the Google Analytics JavaScript and then checking every 250ms to see if it has loaded (i.e. the _gat object has been created). Once it is detected we call the tracking functions required. Simple as that!

TAGS: google | defer | javascript | analytics | onload |