A standard asynchronous Google Analytics tracking code would look like:


<script type="text/javascript">

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-#######-#']);
_gaq.push(['_trackPageview']);

(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

</script>

I didn’t like how they look, so I decided to re-write with jQuery:


if (window._gat) {
_gat._getTracker("UA-#######-#")._trackPageview();
}
else {
$.ajaxSetup({cache: true});
$.getScript(('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js', function () {
_gat._getTracker("UA-#######-#")._trackPageview();
});
$.ajaxSetup({cache: false});
}

It checks if there already is a Google Analytics script included. The script is the same and reusable, some websites might have multiple tracking code being executed. There is no need to create many <script>. If the script isn’t included, then it loads it using jQuery’s getScript(). Within the callback, it logs the pageview. You might also want to put _gat... into a try {} catch.... The older non-asynchronous tracking code does that.

You can also see it uses $.ajaxSetup() to set up cache use. By default, jQuery appends a timestamp like _=1234567890 as a query parameter after the URL of the script you want to load, that timestamp is called cachebuster, which causes web server sends same content to client even the content isn’t modified. I discovered this behavior when I was adding new code on this blog.

In normal request, your web browser will check with server. If server returns 304, then browser will use the ga.js it already has in hand. With cachebuster, that won’t happen, browser receives same content again and again. Using ajaxSetup() is to ensure cache is in use.

The only part I don’t like in my code is how it decides the script link, it doesn’t look pretty to me.