Check If Google Analytics Is In The Page Template


One of the recurring problems in migrating to Google Tag Manager is how to make the transition as smooth as possible. Usually it requires that we agree with the developers on a time when the old code is removed, and at that moment we need to make sure the GTM tags point to the right UA code. This is, of course, only one use case for migrations, as some people do the entire migration in a staging environment, and some just don’t care if they lose a little bit of data along the way.

However, the most seamless way to do the transition is to automate it. Make GTM somehow check for the existence of on-page GA, and if it finds it, the tags will not fire. As soon as the on-page GA is no longer found, GTM can go rampart.

This is a recurring discussion in our Google+ GTM Community, but this time it began in Twitter.

In this post, I wanted to take a shot at what my good friend Peter is looking for, with what I think is the best way to do this.

Now, there are a number of ways you could go about checking for on-page GA, including:

  • Check for existence of GA cookies

    • Very unreliable as cookies persist after removing on-page code, and if migration is to the same version of GA, the cookies are the same
  • Serialize page template, and regex match for script loaders or calls to the tracking objects

    • Crazy solution (that I just came up with), and isn’t very reliable. Fails completely if scripts are loaded in external JS files
  • Ask developers to add dataLayer.push() that tells the status of on-page GA

    • By far the most reliable solution out there, but the reason most people are looking for a solution like this is to minimize developer intervention
  • Check for existence of ga or _gaq objects

    • Works well if you can bear the wait for the tracking library to load AND execute, as the objects are created in the library code. On some sites, this might be a too long wait, especially if the library is loaded asynchronously. Also, you can rename the ga object, so you’d need to identify it first.

But I want to show you what I think is the best way to do it. Feel free to disagree, and I find myself disagreeing with me as well, especially on a complex site! In my opinion, the following solution does the check as early as possible, and it’s as reliable as it can be, even though there are some caveats.


X


The Simmer Newsletter

Subscribe to the Simmer newsletter to get the latest news and content from Simo Ahava into your email inbox!

Solution: look for the

This solution looks for the existence of

We will be happy to hear your thoughts

Leave a reply

Som2ny Network
Logo
Compare items
  • Total (0)
Compare
0