Skip to content

Getting google analytics to play nice with your pages

by Topper on November 24th, 2008

My biggest peeve at the excellent Google Analytics is the fact that it uses document.write to insert its scripts. This can make your page hang for visitors (one blog post I read said up to 5 seconds).

I wrote a tiny library which will use a non-blocking appendChild and then poll for analytic’s existence. All the while you can call your commands where you think they should be called using this format:
[js]
MBX.GoogleAnalytics.run(“_addTrans”, arg1, arg2, arg3);
[/js]

Where the first argument is the string of the command you want to run and then the args are the normal arguments you want to pass in.

If google analytics is unavailable when you execute this command – the command will be cached and run as soon as it is.

Line 57 of this little library depends on the Motionbox EventHandler but it should be trivial to rely on onLoad or another domready from a different javascript library.
[js]
if (!(“MBX” in window)) {
/** @namespace
*/
MBX = {};
}

MBX.GoogleAnalytics = (function () {
var self = {};
var accountId = “UA-YOUR_GOOGLE_ANALYTICS_ACCOUNT”;

var callCache = [];
var pageTracker;
var gaJsHost = ((“https:” == document.location.protocol) ? “https://ssl.” : “http://www.”);
var pollInterval = 300; // ammount of time to check if google is loaded
var _loadedInterval;

var checkIfGoogleLoaded = function () {
if (typeof _gat != ‘undefined’) {
clearInterval(_loadedInterval);
self.activateAnalytics();
}
};

var execStoredCommands = function () {
while (callCache.length > 0) {
self.run.apply(self.run, callCache.shift());
}
};

self.getTracker = function () {
pageTracker = _gat._getTracker(accountId);
};

self.activateAnalytics = function () {
self.getTracker();
pageTracker._trackPageview();
execStoredCommands();
};

self.loadAnalytics = function () {
var analyticsScript = new Element(“script”, {src: (gaJsHost + “google-analytics.com/ga.js”), type: “text/javascript”});
document.body.appendChild(analyticsScript);
_loadedInterval = setInterval(checkIfGoogleLoaded, pollInterval);
};

//arbitrary number of args
self.run = function () {
var args = Array.prototype.slice.call(arguments);
if (pageTracker) {
var command = args.shift();
pageTracker[command].apply(pageTracker, args);
} else {
callCache.push(arguments);
}
};

MBX.EventHandler.onDomReady(self.loadAnalytics);

return self;
})();

[/js]

From → Social Web