Asynchronous Google Analytics snippets (v11)

Revision 11 of this benchmark created on


Description

Test case which measures the speed difference between the default asynchronous Google Analytics snippet and the optimized version. I’ve also added a hardcore optimized version, found on Stack Overflow. (See discussion.)

Note that I commented out the s.parentNode.insertBefore(g, s); line in all scripts, since otherwise the <script> element gets inserted a few thousand times every time you run the tests. Since this code is the same in all scripts, it shouldn’t have an influence on the results.

Preparation HTML

<script id="ga">
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Default snippet
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);
})();
ready
Optimized snippet
var _gaq = [
  ['_setAccount', 'UA-XXXXX-X'],
  ['_trackPageview']
];
(function(d, t) {
  var g = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
  g.async = 1;
  g.src = ('https:' == location.protocol ? '//ssl' : '//www') + '.google-analytics.com/ga.js';
  // s.parentNode.insertBefore(g, s);
}(document, 'script'));
ready
Hardcore snippet
var _gaq;
(_gaq = document.createElement('script')).src = (/^....s/.test(location) ? '//ssl' : '//www') + '.google-analytics.com/ga.js';
(_gaq.a = _gaq.async = document.getElementsByTagName('script')[0]);
//.parentNode.insertBefore(_gaq, _gaq.a);
_gaq = [
  ['_setAccount', 'UA-XXXXX-X'],
  ['_trackPageview']
];
ready
t32k
var _gaq = [
  ['_setAccount', 'UA-XXXXX-X'],
  ['_trackPageview']
];
(function(d, t) {
  var g = d.createElement(t),
      s = d.getElementById('ga');
  g.async = 1;
  g.src = '//www.google-analytics.com/ga.js';
  // s.parentNode.insertBefore(g, s);
}(document, 'script'));
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.