Forum Moderators: open

Message Too Old, No Replies

Analytics asynchronous snippet

How does it work?

         

johnnie

11:41 pm on Dec 9, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I've been happily using Google's new asynchronous analytics code, but one small thing bugs me. Here's the code:

<script type="text/javascript">
var _gaq = _gaq ¦¦ [];
_gaq.push(['_setAccount', 'UA-#*$!#*$!-X']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script');
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
ga.setAttribute('async', 'true');
document.documentElement.firstChild.appendChild(ga);
})();
</script>

Why is the last function() call (the one which creates and inserts the script object) in between brackets? What does it accomplish? And why don't they use window.onload=function(blah blah)....?

Fotiman

4:57 pm on Dec 10, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Using window.onload=... would not be good because it is explicitly setting the event handler for the window. There can only be 1 event handler defined, so that might overwrite some other code on your page, or it might get overwritten by some other code on your page. Also, there's no reason to wait for window.onload to execute.

By doing this:
(function(){...})();

That creates an anonymous function which will execute immediately. That could also have been written like this:
function(){...}();
without the () around the function definition, but it's a common convention to wrap the function in () to indicate that this is not just a function definition, but that its also going to be executed immediately.

The advantage to wrapping things in an anonymous function is that you can create variables without mucking up the global scope. For example, var ga in your example exists only in the scope of the anonymous function, so there's no risk that you're overwriting another global variable. They do still have 1 global variable in use (_gaq), but my guess is that the script that gets pulled in requires access to that global.

johnnie

1:13 am on Dec 11, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thank you!