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. 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 || [];
.push(['_setAccount', 'UA-TRACKING_ID']);

(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '';
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
.push(['_setAccount', 'UA-TRACKING_ID']);
//second tracker
_gaq.push(['othertracker._setAccount', 'UA-OTHER_TRACKING_ID']);

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:
['_setAccount', 'UA-TRACKING_ID'],
['othertracker._setAccount', 'UA-OTHER_TRACKING_ID'],
More info here:


  1. I've never read this before. Thanks for the idea you've shared. I'll come by next time to read more of your posts. I appreciate it for sharing your great idea and great thoughts on us.

    John Mu

  2. Greatt reading your blog post