Archive for the ‘Web Dev’ Category

Unobtrusively add Google Analytics code to a page with jQuery

Monday, July 28th, 2008

The standard analytics code is only 400 bytes or so.. Spread over a few thousand pages that 400 bytes soon eats into your bandwidth costs.

Most of the sites i currently work on use jQuery to add additional functionality without being to obtrusive to people that have JavaScript turned off.

JavaScript has to be turned on for Google’s code to work! So we can safely inject the code when the page is fully loaded and clients that have JavaScript turned off will be none the wiser.

Place the following code into a site wide file that loads after jQuery and change the tracker code (gaTrackCode) to the one you received from analytics.

// google analytics tracking code
jQuery(document).ready(function($) {
  var gaTrackCode = "UA-123456789";
  var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");

  jQuery.getScript(gaJsHost + "google-analytics.com/ga.js", function(){
    var pageTracker = _gat._getTracker(gaTrackCode);
    pageTracker._initData();
    pageTracker._trackPageview();
  });
});