The evolution of ga.js and The best google analytics snippet.

A lot of posts show the blocking problem loading normal javascript files.  To sumarize:  when the browser finds <script src=…, it blocks executing and rendering until js file are downloaded and executed.
Steve Souder presented a complete analysis about the techniques to solve this issue for web performance. I’m using this to load async js files on sonico.com:
(function(d){
   s = d.createElement('script');
   s.src =  'file.js';
   s.type = 'text/javascript';
   (d.getElementsByTagName('head')[0]).appendChild(s);
})(document);
But, I figure out that is better to replace the closure statement by setTimeout funcion and set 0 milisecs. The setTimeout function has a nice performance over IE.  I discovered this trick while watching google.com home page source :P . So, my snippet is:
setTimeout(function(){
   s = document.createElement('script');
   s.src =  'file.js';
   s.type = 'text/javascript';
  (document.getElementsByTagName('head')[0]).appendChild(s);
},0);
The most common 3rd party widget is Google Analytics script, and some time ago google announced a new script improving the loading method. The main changes were: 1) move the script to the end of head tag 2) change the js code like this:
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);
})();
I found a few articles analysing this snippet, for example Mathias that makes some improvements
var _gaq = [['_setAccount', 'UA-XXXXX-X'], ['_trackPageview']];
(function(d, t) {
   var g = d.createElement(t),
   s = d.getElementsByTagName(t)[0];
   g.async = true;
   g.src = '//www.google-analytics.com/ga.js';
   s.parentNode.insertBefore(g, s);
}(document, 'script'));
Another interesting article was writed by HTTPWatch team, they concluded that the new script is not faster than the previous one. But, I think this might be due the fact that they are not testing on a real environment.
I took the Mathias script and change the closure by the setTimeout. My final script is:
var _gaq = [['_setAccount', 'UA-XXXXX-X'], ['_trackPageview']];
setTimeout(function() {
   var g = document.createElement('script'),
   s = document.getElementsByTagName('script')[0];
   g.async = true;
   g.src = '//www.google-analytics.com/ga.js';
   s.parentNode.insertBefore(g, s);
},0);
Another good idea I found is load the script after onload event, using window.onload = function()…  but this idea has the big problem that you can lose tracks if the user goes to other page before the tracker do the mark. So, if you don’t care to lose a few hits, the best is the onload method.
The script:
var _gaq = [['_setAccount', 'UA-XXXXX-X'], ['_trackPageview']];
window.onload = function() {
   var g = document.createElement('script'),
   s = document.getElementsByTagName('script')[0];
   g.async = true;
   g.src = '//www.google-analytics.com/ga.js';
   s.parentNode.insertBefore(g, s);
};

Martin

This entry was posted in wpo and tagged , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

3 Comments

  1. Posted 2010/09/07 at 18:11 | Permalink

    Interesting article!

    If there are no other blocking factors, like for example a big image, using setTimeout(fn, 0) instead of (function() { fn(); }()) might indeed cause the window.onload event to fire sooner. Of course, this change has some implications that might be problematic in some cases, but these don’t apply to this specific case. I’ll try to write a blog post with some more details about this soon.

  2. Posted 2010/10/27 at 16:20 | Permalink

    There is obviously a lot to know about this. I think you made some good points in Features also.
    Keep working ,great job!

  3. Posted 2010/10/28 at 14:32 | Permalink

    Pretty cool, thanks!

2 Trackbacks

  1. [...] evolucion de ga.js y el mejor script de Google Analytics By admin | Published: 2010/09/05 (The english version) Hay un muchos articulos que hablan sobre el problema de bloqueo del browser cuando carga archivos [...]

  2. [...] addMeasure('Perceived Response') Freedev Tips Web Performance Optimization Tips Skip to content About « The evolution of ga.js and The best google analytics snippet. [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">