javascript - Detect if Google Analytics is loaded

2019-01-17 21:05发布

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:

  1. 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.

  2. 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?

10条回答
女痞
2楼-- · 2019-01-17 21:40

I have a different solution for this if anyone cares to try it out. This assumes your Google Analytics Object is 'ga'. Change your timeout and max tries to suit your application.

    <script type="text/javascript">
    var counter = 1;
    function checkIfAnalyticsLoaded() {
        if (window.ga) {
            //LOADED!
        } else {
            counter = counter + 1;
            if (counter < 6){
                setTimeout('checkIfAnalyticsLoaded()', 200);
            } else {
                //LOADED!
            }
        }
    }
    window.onload = checkIfAnalyticsLoaded();
    </script>
查看更多
放我归山
3楼-- · 2019-01-17 21:45
function checkIfAnalyticsLoaded() {
  if (window._gaq && window._gaq._getTracker) {
    // Do tracking with new-style analytics
  } else if (window.urchinTracker) {
    // Do tracking with old-style analytics
  } else {
    // Retry. Probably want to cap the total number of times you call this.
    setTimeout(checkIfAnalyticsLoaded, 500);
  }
}
查看更多
叼着烟拽天下
4楼-- · 2019-01-17 21:45

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);
  }
}
查看更多
闹够了就滚
5楼-- · 2019-01-17 21:52

you may also look into the new Asynchronous Tracking and then you wont need to check you can just do whatever and it will send the data as soon as it loads...

查看更多
forever°为你锁心
6楼-- · 2019-01-17 21:54

Adjusted version to wait for Google Analytics to not only have finished loading, but als have generated the clientId (in case you need it, like I do). Also added a cap on amount of retries (20).

var retryCounter = 0;
function checkIfAnalyticsLoaded() {
  if ((typeof ga === 'function' && ga.loaded) || retryCounter++ > 20) {
    // ga() puts your method in the Command Queue, 
    // which is applied after GA is done with initialization
    ga(yourFunctionHere()); 
  } else {
    // Retry. 
    setTimeout(checkIfAnalyticsLoaded, 500);
  }
}

// Auto load
(function () {
  checkIfAnalyticsLoaded();
})();
查看更多
别忘想泡老子
7楼-- · 2019-01-17 21:57

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

查看更多
登录 后发表回答