I'm working on a project here that will store some info in Google Analytics custom variables. The script I'm building out needs to detect if GA has loaded yet before I can push data to it. The project is being designed to work across any kind of site that uses GA. The problem is reliably detecting if GA has finished loading or not and is available.
A couple of variabilities here:
There's multiple methods of loading GA. Older scripts from the Urchin days up to the latest asynchronous scripts. Some of these are inline, some are asynchronous. Also, some sites do custom methods of loading GA, like at my job. We use YUI getScript to load it.
Variable-variable names. In some scripts, the variable name assigned to GA is pageTracker
. In others, its _gaq
. Then there's the infinity of custom variable names that sites could be using for their implementation of GA.
So does anyone have any thoughts on what might be a reliable way to check if Google Analytics is being used on the page, and if it's been loaded?
Just to go Insights » Reports and click on the Realtime tab. Now, if you see there are active users on your site, then it means Google Analytics is tracking your visitors.
How does Google Analytics work? Google Analytics acquires user data from each website visitor through the use of page tags. A JavaScript page tag is inserted into the code of each page. This tag runs in the web browser of each visitor, collecting data and sending it to one of Google's data collection servers.
This, you can put the code above/before the Google Analytics Tracking Code :
function check_ga() { if (typeof ga === 'function') { console.log('Loaded :'+ ga); } else { console.log('Not loaded'); setTimeout(check_ga,500); } } check_ga();
Demo: http://jsbin.com/rijiyojume/edit?html,console
Or If you can run script after the Google Analytics Tracking Code :
ga(function(tracker) { console.log(tracker.get('clientId')); });
Demo: http://jsbin.com/wiqategifo/1/edit?html,console
Ref: #ready-callback
I'm too lowly to respond to Annie's answer which works but has syntax errors. Analytics names have underscore first and the setTimeout() syntax was backwards (and incomplete). It should be this:
function checkIfAnalyticsLoaded() { if (window._gat && window._gat._getTracker) { // Do tracking with new-style analytics } else if (window.urchinTracker) { // Do tracking with old-style analytics } else { // Probably want to cap the total number of times you call this. setTimeout(checkIfAnalyticsLoaded, 500); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With