javascript 谷歌分析代码解释

rbpvctlc  于 2022-12-25  发布在  Java
关注(0)|答案(6)|浏览(118)

有人能“一步一步地”、“一行一行地”解释这段代码吗?我想了解更多关于异步代码的信息,以及Google如何加载他们的脚本,如何向用户“隐藏”javascript(我知道我不能隐藏它,但至少让它像Google那样,不要在一个文件中显示所有代码)

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

nwlqm0z11#

首先,我将通过一个美化器传递这个函数,例如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];

然后,它将新创建的script标记设置为异步执行(如果需要,可以在Understanding Asynchronous Code in Layman's terms中获得有关异步执行的更多信息)

a.async = 1;

上一行中的1等价于true,使用1只是因为它更短。
然后设置此脚本标记的src

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

请注意,上面的URL中没有指定任何协议(http或https)。这将允许以当前浏览器协议加载脚本。
最后,它被插入到第一个script标记之前,这样浏览器就可以开始加载它了。

m.parentNode.insertBefore(a, m)

所以总结一下:
1.我们创建一个script标记
1.我们将其设置为异步加载async=true
1.我们在文档中的第一个script标记之前插入这个script标记
与谷歌分析相关的细节。

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

定义名为ga的全局函数,该函数将其参数推入队列Array(名为q
再加上台词

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

它将这些“事件”推入队列Array。
加载脚本时,它将检查GoogleAnalyticsObject的值,该值先前通过以下行设置为指向ga的名称

window['GoogleAnalyticsObject'] = 'ga';
insrf1ej

insrf1ej2#

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
兹拉丁的逐行解释仍然有效。

swvgeqrz

swvgeqrz3#

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,然后将该脚本标记添加到文档中。

swvgeqrz

swvgeqrz4#

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

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

tkclm6bt5#

代码已经通过一个小型化器运行过,打印出来后看起来像这样:

(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这样的代码小型化器,它可以替换任何不必要的空格和换行符等,以帮助减少带宽。

5w9g7ksd

5w9g7ksd6#

优化更好的代码:

(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文件,但该文件也被缩小了,因此在我完成this之前,您不会从中获得太多信息。

相关问题