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 probably getting all sorts of insane problems).

If you have any questions, comments or suggested improvements please do hit me up in the comments below.

Recent posts View all

Talk CSS

FrontEnders - Web Performance

Sharing some of my thoughts on a FrontEnders meetup on the topic of Web Performance

Conferences

Tips for how to ask for time off to attend conferences

Asking for time off to attend a conference can be nerve-racking, these tips will get you closer to attending the conferences you're interested in.