How is the Google Analytics Tracking code working? (async method call?)

坚强是说给别人听的谎言 提交于 2019-12-11 19:16:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!