重命名 ga 对象

在某些情况下,您可能希望将 analytics.js 添加到自己的网页,但已将 ga 变量用于其他内容。为解决此问题,analytics.js 提供了一种机制,用于重命名全局 ga 对象。

重命名全局对象

利用 Google Analytics(分析)代码,您可以通过更改传递给 minified 函数的最终参数重命名全局 ga 对象。您还需要更新命令队列中的所有相关调用,将 ga() 改为您选择的任何名称。

例如,如果要将 ga 对象重命名为 analytics,您可以按照以下示例中的方式来更改代码:

<!-- Google Analytics -->
<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','analytics');

analytics('create', 'UA-XXXXX-Y', 'auto');
analytics('send', 'pageview');
</script>
<!-- End Google Analytics -->

手动重命名全局对象

重命名全局对象之所以可行,是因为 analytics.js 会在加载时查找一个字符串(存储在名为 GoogleAnalyticsObject 的全局变量中)。如果找到该变量,就会使用该字符串名作为全局命令队列的新名称。

例如,如果要使用 jQuery 的 $.getScript 方法来加载 analytics.js,您可以使用以下代码来重命名全局对象:

<script>
// Instructs analytics.js to use the name `analytics`.
window.GoogleAnalyticsObject = 'analytics';

// Use jQuery to load analytics.js.
$.getScript('//www.google-analytics.com/analytics.js', function() {

  // Creates a tracker and sends a pageview using the renamed command queue.
  analytics('create', 'UA-12345-1', 'auto');
  analytics('send', 'pageview');
});
</script>

备用异步代码

与标准 Google Analytics(分析)代码不同,备用异步代码没有为重命名全局 ga 对象提供默认支持。

不过,您仍然可以使用上述方法重命名全局 ga 对象,并同时获得备用异步代码的预加载优势。

下面的修订版备用异步代码将 GoogleAnalyticsObject 变量设置为 analytics,还将 ga 的所有实例重命名为 analytics

<!-- Google Analytics -->
<script>

// Instructs analytics.js to use the name `analytics`.
window.GoogleAnalyticsObject = 'analytics';

// Creates an initial analytics() function.
// The queued commands will be executed once analytics.js loads.
window.analytics = window.analytics || function() {
  (analytics.q = analytics.q || []).push(arguments)
};

// Sets the time (as an integer) this tag was executed.
// Used for timing hits.
analytics.l = +new Date;

// Creates a default analytics object with automatic cookie domain configuration.
analytics('create', 'UA-12345-1', 'auto');

// Sends a pageview hit from the analytics object just created.
analytics('send', 'pageview');
</script>

<!-- Sets the `async` attribute to load the script asynchronously. -->
<script async src='//www.google-analytics.com/analytics.js'></script>
<!-- End Google Analytics -->