谷歌分析代码解释

Google Analytics Code Explanation

本文关键字:解释 代码 谷歌      更新时间:2023-09-26

谁能解释一下这段代码'一步一步','一行一行'?我想了解更多关于异步代码和谷歌如何加载他们的脚本,如何"隐藏"javascript从用户(我知道我不能隐藏它,但至少让它像谷歌那样,而不是在一个文件中显示所有代码)

<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>

首先,我会通过美化器传递它,例如http://jsbeautifier.org/

 (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');

之后让我们计算闭包

(function (i, s, o, g, r, a, m) {
...
 })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');

通过将每个命名参数:i, s, o, g, r替换为它们对应的值window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga'

注意am参数没有输入值,更像是结果变量。

这大致相当于

(不考虑变量范围等)
(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');

简而言之,这段代码的本质是创建一个新的脚本标记,行为:

a = document.createElement('script'),

找到第一个脚本标签

m = document.getElementsByTagName('script')[0];

然后它将新创建的脚本标签设置为异步执行(如果需要,可以在Layman's术语中理解异步代码获得有关异步执行的更多信息)

a.async = 1;

1在上面的行中相当于true,它被使用1只是因为它更短。

之后这个脚本标签的src被设置为

 a.src = '//www.google-analytics.com/analytics.js';

注意上面的URL中没有指定协议(http或https)。这将允许脚本在当前浏览器协议中加载。

最后它被插入到第一个script标签之前,这样浏览器就可以开始加载它了。

 m.parentNode.insertBefore(a, m)

所以总结:

    我们创建了一个脚本标签我们将其设置为异步加载async=true
  1. 我们在文档
  2. 的第一个script标签之前插入这个script标签

与google分析相关的细节。

 window['ga'] = window['ga'] || function () {
     (window['ga'].q = window['ga'].q || []).push(arguments)
 }, window['ga'].l = 1 * new Date();

定义名为ga的全局函数,将其参数推入队列数组(名为q)

然后加上

 ga('create', 'UA-xxxxxxxx-x', 'xxxxxx.com');
 ga('send', 'pageview');

它推送这些"事件"

加载脚本时,它检查GoogleAnalyticsObject的值,该值之前被设置为指向ga的名称,行为

 window['GoogleAnalyticsObject'] = 'ga';

Google已经发布了这段代码的未压缩版本:

<!-- 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的逐行解释仍然有效

i['GoogleAnalyticsObject']=r;这是将'ga'分配给'window'的'GoogleAnalyticsObject'属性

window['ga'] = window['ga'] || function(){
        (window['ga'].q = window['ga'].q || []).push(arguments)
    }, window['ga'].l = 1 * new Date();

这部分是将window的'ga'属性赋值为一个函数(或者如果它已经存在的话)。然后,函数将q属性赋值为空数组,并将所有函数参数添加到该数组中。然后,它将当前时间戳赋给l属性(将其乘以1以强制其为整数)。

接下来的几行只是创建一个脚本标签,并为其分配一些属性,如source和async = true,然后它将这个脚本标签添加到文档中。

代码被最小化。使用http://jsbeautifier.org/您可以恢复(排序)并使其更具可读性。基本上它是一个小函数,添加另一个javascript (www.google-analytics.com/analytics.js)到dom使用相同的协议,http或https。

(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');

这段代码已经在一个minifier中运行过了,打印出来后看起来是这样的:

(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');

要知道它到底是做什么的,你可能需要看一看他们的analytics.js文件,但因为它很可能也被缩小了,所以你不会从中得到太多。

如果您想做同样的事情,您可以使用像JSMin这样的代码简化器。它可以替换任何不必要的空格和换行符,以帮助减少带宽。

优化后的代码:

(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');

Google Analytics跟踪入口点已被美化:

(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');

Cixon将// comments添加到此格式化代码:

(function(i, s, o, g, r, a, m) {
    // Pointer - analytics.js uses window['GoogleAnalyticsObject'] to access the string 'ga', sort of a longness of their minified code, that is a problem. But it is to support renaming.
    i['GoogleAnalyticsObject'] = r;
    // Create a GA function if one does not exist, and assign it to window with the string 'ga'. What it does is pushes arguments to the end of an array that is either already defined or is defined in the function
    i[r] = i[r] || function() {
        (/*set to support a case where it is not defined*/ i[r].q = /*if it is already defined, get it*/ i[r].q /*define it here*/ || []).push(arguments)
    };
    // Sets the time (as an integer) this tag was executed.
    // Used for timing hits.
    i[r].l = 1 * new Date();
    // Create the script tag for Google Analytics
    a = s.createElement(o);
    // Get the first script tag
    m = s.getElementsByTagName(o)[0];
    // Set the async property to true (1) and set the src property to the path for Analytics
    a.async = 1;
    a.src = g;
    // Makes this GA tracking code script element (a) go before this 'first script element' (m)
    m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
// Initialize the actual GA runtime
ga('create', 'UA-xxxxxxxx-x', 'xxxxxx.com');
// Send a PageView request to Google Analytics
ga('send', 'pageview');

你能理解注释的代码吗?

要真正理解这个,你必须看一看他们的Analytics.js文件,但那也被缩小了,所以在我完成这个之前你不会从中得到太多。

Google解释如下:https://developers.google.com/analytics/devguides/collection/analyticsjs/tracking-snippet-reference#the-google-analytics-tag

<!-- 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 -->