Checking for both versions of Google Analytics with JavaScript

Here is how I check for both versions of Google Analytics

When writing code that interacts with Google Analytics there are two versions that we need to consider.

  • ga.js
  • analytics.js

analytics.js is the latest and greatest and what Google is pushing people towards using. With the massive adoption rate of Google Analytics on websites it will be some time though before we can forget about good old ga.js.

When introducing a script I wrote to track ctrl+f in browsers I mentioned that I check for both versions of Google Analytics in my code.

I wanted to share the code I used as it may be useful to you at a later date.

if (typeof ga === 'function') {
  ga("send", "event", "Browser Action", "Internal Page Search");
} else if(typeof _trackEvent === 'function') {
  _trackEvent("Browser Action", "Internal Page Search");
} else {
  console.warn("Is Google Analytics correctly set up on this page?");
}

In JavaScript I like to check things at the function level as this is the thing I am actually going to be calling.

What we do here is check for the function ga existing. If it does then we are dealing with the new tracking code and we send the event tracking action using ga().

Next up we check if _trackEvent is a function, this is the old tracking code so we can use the older _trackEvent function.

Finally we fall back to a console.warn – this isn’t necessary and in many cases would be ill-advised. For the purposes of the script I was writing though this seemed good.

The reason I opted for using an if/else if is because if the end user of this script has used both old and new tracking codes then we don’t want our event to double fire (even though they are getting all sorts of problems).


Recent posts View all

Ruby

Forcing a Rails database column to be not null

How you can force a table column to always have something in it with Rails

Writing Marketing

We've deleted an article's worth of unhelpful words

We've improved several pages across our site by removing words that add no value, and often detract from the article.