Or: Still ending the ga.js wait…
It has become quiet here the last weeks – due to an awesome trip to Italy. Returning home, I decided to put Google Analytics on this page.
As I always hate waiting for the ga.js to load while visiting websites, I wanted a mechanism to delay the load of it. Why this is a good idea has been discussed often enough elsewhere, so we take it as fact. Peter Higgins once wrote such a wrapper for dojo, and as of dojo 1.3, it’s officially included in dojox (see Alex Russel’s post). But this WordPress theme runs jQuery, and I didn’t want to have two frameworks in one website – so I searched for something that did the job for jQuery.
But I didn’t really find what I was looking for. Well, there are some jQuery plugins that provide functionality like I wanted. Some were overpowered, some poorly written – and in the end, they all relied on jQuery.getScript(). The problem is, that getScript() adds a random parameter to the GET call, so that the called script is never cached. While this may be useful for some situations, in this case it’s really annoying and undesireable. In addition, I liked the idea of dojox.analytics.Urchin to not really wait for the script to be loaded, but instead to go see every now and then if the _gat global variable is present, and to give up after some time in case something went wrong.
So I decided to “port” dojox.analytics.Urchin to jQuery. It works almost the same as it’s dojo origin, with two major differences: First, you can’t have several instances of it running, you call it directly via jQuery.urchin.load(args). Second, there’s an option waitForDOM, set to true as default, that delays the loading of ga.js until the DOM is ready. If you call jQuery.urchin.load() from within a jQuery(document).ready() block, set this to false.
Example? Here you go:
Or, if you need more options:
You can get the file here: jquery.urchin.js
Uncompressed version: jquery.urchin.uncompressed.js