4
votes

I am trying, through javascript, to identify if Google Analytics or Universal Analytics is loaded.

Some clients still use the old Google Analytics and we want to roll out a javascript that collects data. So i then need to write code for both versions to make sure it gets tracked regardless if its the normal or universal version of analytics.

3
When you say old, you're talking about the version directly before the analytics.js stuff, right? How far back do you need to go? You don't need to go back to the Urchin days, do you? - Brad
Nope, just Google analytics and Universal analytics. - Patrick

3 Answers

9
votes

Classic GA uses the "_gaq" object, and UA uses the "ga" object, so you could check for the existence of either of those

if (_gaq) {
   // using classic GA; do whatever
}

or

if (ga) {
   // using UA; do whatever
}

Hope this helps.

2
votes
if (typeof window.ga === 'undefined') {
   // analytics does not exist
}
1
votes

From https://developer.mozilla.org/en-US/Firefox/Privacy/Tracking_Protection:

<a href="http://www.example.com" onclick="trackLink('http://www.example.com', event);">Visit example.com</a>
<script>
function trackLink(url,event) {
    event.preventDefault();
    //This is how you check that google analytics was loaded
    if (window.ga && ga.loaded) {
         ga('send', 'event', 'outbound', 'click', url, {
         'transport': 'beacon',
         'hitCallback': function() { document.location = url; }
       });
    } else {
        document.location = url;
    }
}
</script>