Unobtrusively add Google Analytics code to a page with jQuery
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();
});
});
December 22nd, 2008 at 4:45 pm
Hi-
This looks like a very nice way to load Google Analytics on my sites already using jQuery, because it won’t block the DOM loading while pulling in the tracking code. However, I have tried to implement this on one site as a test and Google keeps telling me that the tracking code has not been detected on my site. Have you run into this problem at all?
btw, there is new Google code to execute after script is called, it looks like:
try {
var pageTracker = _gat._getTracker(gaTrackCode);
pageTracker._trackPageview();
} catch(err) {}