ahmad Ahmad Nassri Blog

A faster Google Analytics implementation

Google's snippet for Analytics is optimized for maximum compatibility, not for performance. Here's how to make it faster.

Google suggests using the following asynchronous syntax to load Google Analytics JavaScript for websites:

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXX-X']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

Which dynamically determines whether the HTTP protocol for the requested page is either secure or standard. It then uses the appropriate protocol to reference the tracking code. So, if one page on your site is delivered over a standard HTTP protocol, the result is:

<script src='http://www.google-analytics.com/ga.js' type='text/javascript'></script>

If another page is delivered over a secure connection, the result will be:

<script src='https://ssl.google-analytics.com/ga.js' type='text/javascript'></script>

This is the popular technique for loading none-blocking JavaScript, but depending on your needs, you can simply just use the appropriate script from above directly.

The problem with that you still have to do do the HTTP/HTTPS detection dynamically to determine the correct file to load, which is a bit too much for my taste (even if it has zero or no impact on performance).

Lets make it better

My needs are specific, and I don’t want to blindly use the JavaScript snippet Google provided, so the first thing I did was test the two different URLs on both HTTP and HTTPS.

First I tried http://ssl.google-analytics.com/ga.js which seems to redirect to https://ssl.google-analytics.com/ga.js so that’s no good (forcing HTTPS)!

www.google-analytics.com/ga.js however seems to work on both (while inheriting the page’s protocol) taking that a step further, strip www and it also works as expected (less typing = better).

(for sanity and paranoia’s sake, I downloaded both sources and compared them to make sure they are identical)

So from now on, I’ll probably stick to using the following:

<script type="text/javascript">
  var _gaq = _gaq || []
  _gaq.push(['_setAccount', 'XXX'])
  _gaq.push(['_trackPageview'])
</script>
<script type="text/javascript" async src="//google-analytics.com/ga.js"></script>

Which is much shorter and more efficient.