Non-blocking Google Analytics Revisited

11 May 2009 tags:

UPDATE: I have updated this code in a more recent post and have also stuck it in my git repository to track changes.

I recently posted about my use of some Javascript code to reduce the blocking of Google Analytics inclusion. Well the code I was using was quite generic and was written to use jQuery, YUI2 or YUI3. It also does not use a technique that I now prefer and along with the extra code that I will never use (I use jQuery exclusively) meant I needed to come up with something better.

I am now using some Javascript code that is based on Steve Souder’s very interesting tips to faster web sites. He outlines a number of techniques to get your sites loading JavaScript in an optimal way

Basically all it does is insert the script loading into the head of the document and then waits for the ‘onreadystatechange’ or the ‘onload’ function to be called. When it is complete (readyState is 4) then it calls the tracking code from Google Analytics.

function gaLoad (key) {
  // account for SSL
  var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
  var tracker;
  var script;
  script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = gaJsHost + 'google-analytics.com/ga.js';
  script.loaded = false;

  // call the GA tracker
  function track () {
    tracker = _gat._getTracker(key);
    tracker._trackPageview();
  }

  // set up the hooks
  script.onload = function () {
    script.loaded = true;
    track();
  };
  script.onreadystatechange = function() {
    // test that it is complete(4), exists(200) and hasn't already been loaded
    if (script.readyState == 4  && !script.onloadDone && script.status == 200) {
      script.loaded = true;
      track();
    }
  };

  // insert the script into the head
  document.getElementsByTagName('head')[0].appendChild(script);
}

This can then be loaded anywhere in your page by simply calling the ‘gaLoad’ method with your Google Analytics key/account number.

gaLoad('UA-111111');

In fact, it can be loaded after absolutely everything has finished loading, scripts, CSS and images included. Beware that if people move off your page before the last item is downloaded you will miss the page count.

window.onload = function(){ gaLoad('UA-111111'); };

Now you can really push that Google Analytics code as the last thing on your page.


Possibly Similar Pages


Comments on this post

blog comments powered by Disqus
loading