In the Google Analytics tracking code, why do they use closure

Why do they end these lines in closure in the Google Analytics tracking code?

(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); })(); 

Would this not work without closing the parent?

+6
source share
2 answers

It will work the same way, but it can easily break other scripts on your page if you specify a variable with the identifier used in the Google code.

Concluding the declaration in close, the variables are bound to an anonymous function and do not leak into the global scope.

For example, consider this example with a new scope:

 var ga = "something important for my script"; // Not overwritten in this scope (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); })(); 

And this example without it:

 var ga = "something important for my script"; // Overwritten! 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); 
+7
source

It will work the same way until global scope variables are defined using the same name. The wrapper code in the closure puts it in its own volume so that it does not depend on any other code on the page.

+3
source

All Articles