重新命名 GA 物件

在某些情況下,您想在網頁中加入 analytics.js,但 ga 變數已用於其他用途。為解決這個問題,analytics.js 提供重新命名全域 ga 物件的機制。

重新命名全域物件

Google Analytics (分析) 代碼可讓您變更傳送至壓縮函式的最終參數,藉此重新命名全域 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 -->