Improve Google Analytics load delays using jQuery

by Blake Schwendiman on May 14, 2009

I’ve spoken about the complex interdependencies of modern web applications before so today’s massive failure of Google services (#GoogleFail) reminds us again to be careful and deliberate when building our applications.

For my own sites, I’ve noticed occasional slowdowns while loading Google Analytics. While the analytics are important to me, they’re not important to you (my readers) and if waiting for a component to load causes a bad experience on the site, you assume it’s just a bad site.

Fortunately there is (as always) a jQuery option to help mitigate this problem. I found one solution called the jQuery Google Analyics plugin that does much more than just defer the loading of Google Analytics, but the key feature I was looking for was the deferral. This plugin appears to be a good solution to the problem and if you study the source code, you’ll see that making your own deferred Google Analytics loader shouldn’t be too hard.

I haven’t tried it yet, but it looks like the code will be something like this:

[-]?View Code JAVASCRIPT
function load_and_track_ga() {
  var account_id = 'UA-XXX-XXX';
  var host = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
  var src = host + 'google-analytics.com/ga.js';
    $.getScript(src, function() {
      if (typeof _gat != undefined) {
        pageTracker = _gat._getTracker(account_id);
        pageTracker._trackPageview();
      }
      else {
        throw "_gat is undefined";
      }
    });
  }
}

What are your thoughts? Have you tried this or something like it? Does it improve your site performance?

Comments:

Comments on this entry are closed.