If you find yourself managing a few sites or clients who are on different versions of Google Analytics, you might find that code reuse to record and track website visitor usage a little frustrating. You might even find the task of moving to the newest version of Google Analytics daunting as event trigger code will surely break.

In a previous post, Google Analytics code snip-its to add download and event tracking to your content (Nov 7, 2015), I went over a way to hard code an onClick event that triggers Google Analytics event reporting. In the code I left it up to the developer to comment in/comment out which analytics version they were using. However, since then I’ve come across a third version one of my clients was using and wondered, “Gee, wouldn’t it be great if my code could automatically detect which version?”

Now, posting such a thought to an online coding forum will quickly get you a response like:

CrabbyCoder4872: you should upgrade to Universal Analytics

OK, yeah, great. I do that on my own sites where I have control, but I manage some where the version of Google Analytics that is used heavily depends on what is coded in the Content Management System template. And yes, the web folks are planning an upgrade, but for large sites that doesn’t just happen overnight especially when things like event calls are implemented for older versions. And when the upgrade does happen, it is even better if my scripts can just auto-detect the change and start using the new code without breaking.

So, that got me to the following helper functions for either tracking events (t_RecordEvent) or pageviews (t_RecordPageView) which were tested and found to work OK on the sites I manage but if you changed any of the variables you might find mixed results so use/modify at your own risk!:

Here is an example of use:

This was all tested using the following Google Analytics script tags (change UA-xxxxxxxx-x to your own and comment out the script you aren’t testing for. (Only include one at a time!)

So, there’s the code with no written, implied, or expressed warranty. I’m still working on jQuery that will add event handlers for downloads and other trackable events, and yes, Google Tag manager would do lots of that but if not all of my sites are upgraded to Universal Analytics then I’ve got to be able to fall back on something.

Happy coding!

About Chad Leigh Kluck

I enjoy technology development and management by following new trends, change and disruption, and security. I have a Master of Science in Software Engineering and my hobbies include railroads, history, do-it-yourself projects, writing, and ham radio (K0RRX). More...

I enjoy comments and feedback. Let me know if you have anything to share with me like stories, pictures, or other media. You can also contact me directly via the contact form. I'd love to hear from you!

Leave comments or feedback