Update: This post was live for about 5 minutes before Michael in the comments brought Google’s official asynchronous solution to my attention. That’s probably a much better way to go. I’ll leave the original post here as google bait though…
I’ve gone ahead and moved the loading and execution of the GA javascript into an external file so as to speed up loading of the page and not delay firing of the onload event.
For every page you want tracked, make sure to include a div (or any element) with the id “ga-pageview-tracking” and include the javascript file shown below.
It’s fairly simple, and I’ve extracted the core of it into a single javascript file. I thought about uploading it to github, but it’s just so tiny.
(function($){
var GA_ID = "PUT-YOUR-GA-ID-HERE";
function gaTrackPageview() {
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
var src = gaJsHost + "google-analytics.com/ga.js";
if($('#ga-pageview-tracking').length) {
$.getScript(src, function(data, textStatus) {
var tracker = _gat._getTracker(GA_ID);
tracker._trackPageview();
});
}
}
$(document).ready(function() {
gaTrackPageview();
});
})(jQuery);
March 11th, 2010 at 11:58 am
Have you looked into the asynchronous tracking beta for Google Analytics?
http://code.google.com/apis/analytics/docs/tracking/asyncTracking.html
March 11th, 2010 at 12:05 pm
Thanks. I’ll update the post. Using the official Google method is probably better.