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?
Google Analytics' tracking code (or ID) is a unique identifier that allows Google Analytics to collect data when inserted into a website. This data includes the time users spend on a webpage, search terms used, and how they came to the site. The tracking code is the mechanism by which Google Analytics compiles data.
On July 1, 2023, standard Universal Analytics properties will stop processing new hits. If you still rely on Universal Analytics, we recommend that you prepare to use Google Analytics 4 going forward.
The tracking ID is a string like UA-000000-2. It must be included in your tracking code to tell Analytics which account and property to send data to.
Every time a user visits a webpage, the tracking code will collect anonymous information about how that user interacted with the page. For the Google Store, the measurement code could show how many users visited a page that sells drinkware versus a page that sells houseware.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With