Google Analytics Code Explanation
Google Analytics Code Explanation
问题
Can someone explain this code 'step by step','line by line'? I would like to learn more about Asynch code and how Google loads their script, how to 'hide' javascrippt from users (I know that I can't hide it but at least make it something like Google does, not to show all code in one file)
<script>
(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-xxxxxxxx-x', 'xxxxxx.com');
ga('send', 'pageview');
</script>
回答1
First of all, I would pass this through a beautifier, e.g. http://jsbeautifier.org/
格式化的网站,域名换了https://beautifier.io/
(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-xxxxxxxx-x', 'xxxxxx.com');
ga('send', 'pageview');
After that lets evaluate the closure
(function (i, s, o, g, r, a, m) {
...
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
by replacing each of the named parameters: i, s, o, g, r
with their corresponding values window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga'
Note that a
and m
parameters do not have input values and are more like result variables.
This would be roughly (not bothering about variable scope, etc.) equivalent to
(function (i, s, o, g, r, a, m) {
window['GoogleAnalyticsObject'] = 'ga';
window['ga'] = window['ga'] || function () {
(window['ga'].q = window['ga'].q || []).push(arguments)
}, window['ga'].l = 1 * new Date();
a = document.createElement('script'),
m = document.getElementsByTagName('script')[0];
a.async = 1;
a.src = '//www.google-analytics.com/analytics.js';
m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-xxxxxxxx-x', 'xxxxxx.com');
ga('send', 'pageview');
In short what this code does in essence, is that it creates a new script tag with the line:
a = document.createElement('script'),
Then finds the first script tag
m = document.getElementsByTagName('script')[0];
Then it sets the newly created script tag to asynchronous execution (More insight on async execution could be obtained at Understanding Asynchronous Code in Layman's terms should you need it)
a.async = 1;
1 in the line above is equivalent to true
, it is used 1 just because it is shorter.
After that the src of this script tag is set
a.src = '//www.google-analytics.com/analytics.js';
Note that above no protocol (http or https) is specified in the URL. This would allow for the script to be loaded in the current browser protocol.
And finally it is inserted before the first script tag, so the browser could start loading it.
m.parentNode.insertBefore(a, m)
So to summarize:
- We create a script tag
- We set it to load asynchronously
async=true
- We insert this script tag, before the first script tag in the document
Specifics related to google analytics.
window['ga'] = window['ga'] || function () {
(window['ga'].q = window['ga'].q || []).push(arguments)
}, window['ga'].l = 1 * new Date();
defines global function named ga
that pushes its arguments in a queue Array (named q
)
Then with the lines
ga('create', 'UA-xxxxxxxx-x', 'xxxxxx.com');
ga('send', 'pageview');
it pushes these "events" in the queue Array.
When the script is loaded, it checks the value of GoogleAnalyticsObject
, which earlier was set to point to the name of ga
with the line
window['GoogleAnalyticsObject'] = 'ga';
Hope this helps
回答2
Google has published the un-minified version of this code:
<!-- Google Analytics -->
<script>
/**
* Creates a temporary global ga object and loads analytics.js.
* Parameters o, a, and m are all used internally. They could have been
* declared using 'var', instead they are declared as parameters to save
* 4 bytes ('var ').
*
* @param {Window} i The global context object.
* @param {HTMLDocument} s The DOM document object.
* @param {string} o Must be 'script'.
* @param {string} g Protocol relative URL of the analytics.js script.
* @param {string} r Global name of analytics object. Defaults to 'ga'.
* @param {HTMLElement} a Async script tag.
* @param {HTMLElement} m First script tag in document.
*/
(function(i, s, o, g, r, a, m){
i['GoogleAnalyticsObject'] = r; // Acts as a pointer to support renaming.
// Creates an initial ga() function.
// The queued commands will be executed once analytics.js loads.
i[r] = i[r] || function() {
(i[r].q = i[r].q || []).push(arguments)
},
// Sets the time (as an integer) this tag was executed.
// Used for timing hits.
i[r].l = 1 * new Date();
// Insert the script tag asynchronously.
// Inserts above current tag to prevent blocking in addition to using the
// async attribute.
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');
// Creates a default tracker with automatic cookie domain configuration.
ga('create', 'UA-XXXXX-Y', 'auto');
// Sends a pageview hit from the tracker just created.
ga('send', 'pageview');
</script>
<!-- End Google Analytics -->
https://developers.google.com/analytics/devguides/collection/analyticsjs/tracking-snippet-reference
Zlatin's line by line explanation is still valid.
把Google analytics script 放在one trust script 后面
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2021-04-26 Customising the browse for folder dialog to show the path
2019-04-26 正则匹配IP