I have JavaScript code that is currently used in analytics.js to call various custom events, but I'd like to prepare it to support the new Google Analytics 4.
I've recently upgraded the site to gtag.js in my local environment, and was planning to make sure all of its custom events/ecommerce tracking/etc is working properly, then set up an Analytics 4 installation and migrate to it.
I'd like to set up a script that would detect which version of Analytics is running and would call the JavaScript syntax for that version, but I'm having trouble figuring out if this is reliable.
Here is my first attempt:
if ( typeof gtag !== 'undefined' ) {
var params = {
'event_category': category,
'event_label': label
};
if ( typeof value !== 'undefined' ) {
params.value = value;
}
gtag( type, action, params );
} else if ( typeof ga !== 'undefined' ) {
if ( typeof value === 'undefined' ) {
ga( 'send', type, category, action, label );
} else {
ga( 'send', type, category, action, label, value );
}
}
I notice that this does run my events as I would expect in the gtag.js install (I'm running it with this GA Debug plugin in Chrome). The ga portion is what is running on our production site, so I know that it works as well.
However, in the Analytics.js version gtag is (sometimes) already loaded because of old Google AdWords installations. Detecting whether gtag is defined would return that it's true, in these cases.
But on the flip side, I've noticed that even when gtag.js is the only version of Analytics that is running, detecting whether ga is defined also returns true. Presumably because at least in the legacy version of gtag.js, it contains a wrapper around analytics.js.
Is there any reliable way of detecting in JavaScript whether analytics.js or gtag.js is being used specifically for Analytics, or would I need to handle this on the server side before it gets this far?