2015年4月24日 星期五

如何在網站上埋多個 universal GA tracking code?

昨天凌晨 12 點,正當我準備進入彌留狀態時,有朋友敲了敲我,說:
Ruby~不好意思想問一個小問題,我們網站剛改版,這兩天跳出率都超低,只有0.xx%... 這是改版後正常的情況嗎?
跳出率 0.xx% 這真的不是正常狀況,而且一定是哪裡有問題!結果後來發現,是因為網站埋了兩個 Universal GA tracking ID 卻沒有正常宣告。

一般的  Universal GA tracking ID 是長這樣的:

<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', 'auto');
ga('send', 'pageview');

</script>

但如果要在網頁上放兩組的 GA code,已經不像是舊版 ga.js 一樣,直接把取用的兩組 code 貼在網頁上即可,code 必須要有所調整。新版 GA 必須把 cookie 個別命名,不然流量數字都會被記到第一組 GA tracking ID 對應到的 property 上,造成有一組報表上的 hit 全部多了一倍,一次的 pageview 被算了 2 次,當然跳出率超低。另一組報表上的數字則是空空如也。

所以如果要調整 code 的話,方法如下:

<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', 'auto');  //建立第一組 cookie,並使用預設命名
ga('send', 'pageview'); //傳送 pageview

ga('create', 'UA-xxxxxxxx-x', 'auto', {'name': 'ruby'}); //建立第二組 cookie,並命名為 Ruby
ga('ruby.send', 'pageview'); //傳送一個 pageview 到 ruby cookie 中

</script>

當然,命名可以改成其他的名字 XD
祝大家

Have fun with Google Analytics!


沒有留言: