重新命名 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 -->