Forum Moderators: open
<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)....?
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.