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

Web Dev

Updating payment method email addresses in Stripe

You can't update the email address associated with a payment method in Stripe via their dashboard, you need to use the Stripe CLI

Ruby

Irreversible Rails Migrations

What are irreversible migrations and how might we use them to our advantage?