Load Google Analytics asynchronously

So at some point last week I realized that Google Analytics was slowing down DNZO‘s page loads. I had just been using the default Google Analytics loader code, which spits out its <script> blocks inline. That behavior causes the browser to load the tracking stuff before continuing with anything else, and that’s not cool.

After some searching I found a blog post at Ajaxian that talks about the issue. I didn’t immediately find a Prototype-based solution for Analytics in particular, however.

So I wrote a bit of Prototypey JS to write the elements out once the page is loaded, and I’ve noticed a dramatic improvement in page load time.

Here’s the code; it’s pretty straightforward:

<script type="text/javascript">
function _checkGAT() {
  if (typeof _gat == 'undefined') { 
    setTimeout(_checkGAT, 200); 
  } else {
    try {
      var pageTracker = _gat._getTracker('UA-123456-7');
      pageTracker._trackPageview();
    } catch(err) {}
  }
}
Event.observe(window, 'load', function(e) {
  $$('head').first().appendChild(new Element('script', { 
      src: ("https:" == document.location.protocol) ? 
            "https://ssl." : "http://www." +
            "google-analytics.com/ga.js"
     }));
  _checkGAT();
});
</script>

Hopefully someone finds this useful. ;)

Comments on “Load Google Analytics asynchronously”

There are no comments on this entry yet.

Add a comment

Thanks for visiting! Looking for more? Check out the archives.