Multiple Google Analytics Tracking Codes on one Page

published Nov 11, 2011

Say I want to make it so that Leanpub authors can get Google Analytics information about visits to their page while still sending the info to our Leanpub analytics account. This is pretty easy to do, but finding out how took me a bit of googling.

Your google analytics script for a normal, single tracking code looks something like this:

      var _gaq = _gaq || [];
      _gaq.push(['_setAccount', 'UA-1234567-1']);
      _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);
      })();

That’s all fine and dandy, but what if you want to have two codes in there?

Turns out it’s pretty simple. You add another set of _gaq.push lines, right after the current ones and before (function() {. Something like this:

      _gaq.push(['account2._setAccount', 'UA-1234567-1']);
      _gaq.push(['account2._trackPageview']);

The account2 part can be anything you want. In fact, you can stick in a bunch of them if you want, resulting in something like this:

      var _gaq = _gaq || [];
      _gaq.push(['_setAccount', 'UA-1234567-1']);
      _gaq.push(['_trackPageview']);
      _gaq.push(['account2._setAccount', 'UA-1234568-1']);
      _gaq.push(['account2._trackPageview']);
      _gaq.push(['account3._setAccount', 'UA-1234569-1']);
      _gaq.push(['account3._trackPageview']);
      _gaq.push(['account4._setAccount', 'UA-1234570-1']);
      _gaq.push(['account4._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);
      })();

Nice!

More info can be found here: http://code.google.com/apis/analytics/docs/tracking/asyncUsageGuide.html#MultipleCommands.

blog comments powered by Disqus