Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

javascript - Detect if Google Analytics is loaded yet?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...