Google Analytics Asynchronous Tracking Code

Perm url with updates: http://xahlee.org/js/google_analytics_tracker_code.html

Google Analytics Asynchronous Tracking Code

Xah Lee, 2010-07-01

Few months ago, google released a new tracking code for Google Analytics, featuring asynchronous javascript. If you haven't updated yet, you should do it now. It increases your page load speed noticeably. When during busy times such as morning or noon, it speeds up 1 second or more.

Note that saving a fraction of a second matters. See: Speed Matters (2009-06-23) by Jake Brutlag. Source

This is their old code, in 2 blocks of javascript:

var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
try {
var pageTracker = _gat._getTracker("UA-xxxxxxxx-x");
pageTracker._trackPageview();
} catch(err) {}

This is their new code:

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-xxxxxxxx-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);
  })();

Some Analysis of The New Code

Let's study this new code a bit.

You can see that it first creates the variable “_gaq” if it is not already defined. Then it defines a anonymous function by:

function() {...}

then call it at the same time by

(function() {...}) ()

This is commonly known as lambda function or function expression.

The function basically constructs the following html code and insert it into the page.

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

(or https version at “https://ssl.”.)

Now let's look at the js code “ga.js”. It is a condensed and obfuscated js code. It has a total of 25k chars. It has 839 “;”, and 383 “{}” pairs, and the “function” definition happens about 254 times. If you expand the code into lines, it's about over 1k lines, more likely close to 2k lines. See the files here:

The code seems to use a lot advanced functional programing, with lots of function expressions.

Popular posts from this blog

11 Years of Writing About Emacs

does md5 creates more randomness?

Google Code shutting down, future of ErgoEmacs