Two analytics on one page

2020-04-24 17:19发布

问题:

How can i put two GA codes on a site. I have this code:

(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-55738390-2', 'auto');
        ga('create', 'UA-55738390-3', 'auto');
        ga('send', 'pageview');

But the 2nd analytics code is not working. How can i fix this?

回答1:

Your second tracker is overriding the first. It's not per se a problem to have multiple trackers per website, but you need multiple pageview (or other interaction) calls as well. Best way to do this is to use named trackers:

ga('create', 'UA-XXXX-Y', 'auto', 'tracker1');
ga('tracker1.send', 'pageview');
ga('create', 'UA-XXXX-Y', 'auto', 'tracker2');
ga('tracker2.send', 'pageview');

That way you can make interactions calls to specific trackers by prefixing the tracker name to the send method call.