Light Dark
Ahmad Nassri

Co-Founder of Cor, Fractional CTO, Developer Accelerator, Startup Advisor, Entrepreneur, Founder of Tech Masters Community.

Previously: npm, TELUS, Kong, CBC/Radio-Canada, BlackBerry


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']);

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


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='' type='text/javascript'></script>

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

<script src='' 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 which seems to redirect to so that’s no good (forcing HTTPS)! 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'])
<script type="text/javascript" async src="//"></script>

Which is much shorter and more efficient.