问题
This code is the Google Analytics tracking code. How is not make an error because of undifened ga method?
(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-XXXX-Y', 'auto');
ga('send', 'pageview');
回答1:
Expanded, the script looks like this:
(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-XXXX-Y', 'auto');
ga('send', 'pageview');
You'll notice that 'ga'
is the fifth parameter passed to the function, and window
is the first. Inside the initialization, the first couple lines set i[r]
, aka window['ga']
to a function. And there you go!
来源:https://stackoverflow.com/questions/23474151/how-is-the-google-analytics-tracking-code-working-async-method-call