Wednesday, December 21, 2011

How to use multiple google analytics trackers on the same page

Today I faced a problem with how to use multiple trackers for Google Analytics on the same page.
"Why would I have to to that?" you may ask.
Well...in this case we needed to track statistics for a global campaign site where both the global marketing departement and the local markets needed to get statistics for the campaign.
The tracking ID's are stored in EPiServer and loaded dynamically of course.

The solution for the problem was not very advanced but not completely obvious.

To set up an asynctracker you start by adding this snippet of code:

var _gaq = _gaq || [];
_gaq
.push(['_setAccount', 'UA-TRACKING_ID']);
_gaq
.push(['_trackPageview']);

(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga
.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

But as you can see, there is only one tracking ID here.
To add one more tracker, one might be tempted to add another _gaq object. But the solutions is actually more simple than that!

var _gaq = _gaq || [];
//first tracker
_gaq
.push(['_setAccount', 'UA-TRACKING_ID']);
_gaq
.push(['_trackPageview']);
//second tracker
_gaq.push(['othertracker._setAccount', 'UA-OTHER_TRACKING_ID']);
_gaq
.push(['othertracker._trackPageview']);

As you can see, it just is a matter of adding another namespace for the new tracker!
It is also possible to do it all in one push(), like below:
_gaq.push(
['_setAccount', 'UA-TRACKING_ID'],
['_trackPageview'],
['othertracker._setAccount', 'UA-OTHER_TRACKING_ID'],
['othertracker._trackPageview']
);
More info here:
http://code.google.com/apis/analytics/docs/tracking/asyncUsageGuide.html
http://seo-website-designer.com/Google-Analytics-Tracking-Multiple-Accounts