場合によっては、analytics.js をページに追加しようとしても、ga
変数がすでに別の場所で使用されていることがあります。このような状況に対応するため、analytics.js には、グローバル ga
オブジェクトの名前を変更する機能があります。
グローバル オブジェクトの名前を変更する
Google アナリティクス タグでは、短縮された関数に渡される最後のパラメータを変更することで、グローバル 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 アナリティクス タグと異なり、デフォルトの代替の非同期タグでは、グローバル 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 -->