简体   繁体   中英

In the Google analytics tracking code, why do they use a closure

Why in the google analytics tracking code, do they wrap these lines in a closure?

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

Wouldn't it work the same without the parent closure?

It would work the same, but it could easily break other scripts on your page, if you've declared a variable with an identifier used in the Google code.

By wrapping the declaration in a closure, the variables are scoped to the anonymous function and don't leak to the global scope.

For example, consider this example with the 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);

It would work the same as long as there were no global scope variables defined using the same name. Wrapping the code in a closure places it in its own scope so that it is independent from any other code on the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM