#analysation #demystify #minify #tracking
Provides an instant overview of your shop's current customers and the contents of their carts.
When reducing your HTTP requests for front-end optimization reasons, one will eventually stumble upon the Google Analytics (GA) snippet. The GA snippet triggers an asynchronous request to download the analytics.js file from Google servers from the moment the snippet is processed on your page. Because it is asynchronous (in the browsers that support this behavior) it won’t block further script loading/execution and DOM rendering much, but it is still an extra HTTP request, DNS lookup, dependence on a server you do not control, etc. So for the situations you might want to host the analytics.js script yourself and/or combine it with your other scripts, let’s document how to do so.
Note that this is not encouraged (by Google) because loading it remotely ensures it will always be the latest version including the newest features.
Here’s the current (it has changed way too often) snippet that GA gives you:
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-########-#', 'auto');
ga('send', 'pageview');
When unminifying it, it becomes easier to understand:
(function(){
window['GoogleAnalyticsObject'] = 'ga';
window['ga'] = window['ga'] || function(){
window['ga'].q = window['ga'].q || [];
window['ga'].q.push(arguments);
},
window['ga'].l = 1 * new Date();
var a = document.createElement('script');
var m = document.getElementsByTagName('script')[0];
a.async = 1;
a.src = '//www.google-analytics.com/analytics.js';
m.parentNode.insertBefore(a, m);
})();
ga('create', 'UA-########-#', 'auto');
ga('send', 'pageview');
So… the snippet adds an object window.ga
which is by itself callable as a function, but also contains the array “q” and the variable “l”. Q being an array of actions to perform (a queue), and L being a timestamp. It then inserts a script tag to load the external script, which whenever it is loaded – this is unpredictable since it is asynchronous – will process the values from the global variables. When ga()
is called later on, it adds whatever arguments it is given as an array to the “q” array inside itself.
Posted by Berend on
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>