开发者

How to make sure Google Analytics loads even if user navigates away from page?

I'开发者_运维问答m not sure what happens when a page containing the asynchronous version of Google Analytics hasn't fully loaded but the user either closes the browser or navigates to another page.

If the analytics doesn't get recorded like I assume, then what methods are available to ensure that it does?

If it does, how does it work?


This is probably impossible. You can kind of reverse-engineer google analytics stuff by tracking the resources they add to the page, like this:

var googleAnalyticsDidTheThing = false;
// ga_src is the src to a script that Google dynamically adds to your page
// this is your asynchronous code
var ga_src = "something.google.com/ga.js";
var ga_script;
var id = setInterval(function () {
  var scripts = document.getElementsByTagName("script");
  for (var i=0, len=scripts.length; i<len; i++) {
    var script = scripts[i];
    if (script.src === ga_src) { ga_script = script; break; }
  }

  var cb = function () {
    googleAnalyticsDidTheThing = true;
  };

  ga_script.onload = cb;
  // This one's for IE
  ga_script.onreadystatechange = function () {
    if (this.readystate === "complete") cb();
  }
}, 50);

But the problem is that only gets you halfway there. You can check to see if it's done by using window.onunload as @nidhin mentioned. However, since javascript is single-threaded, only one process can be taking place at a time. So, I see no way for you to block the user from exiting the page without also blocking ga_script's ability to run in the background. Hence, you can check to see if Google has finished doing their thing, but you can't actually make sure Google can finish.

You could, however, send some info to your own server (the page could leave, but the data would still get sent) and gather statistics on how many users actually do this, to get a feel for what your margin of error is. You could even attempt to do some of the tracking yourself, if you are really determined.


You can check Google analytics is loaded before window is closed like this

<script type="text/javascript">

window.onunload = checkIfAnalyticsLoaded;

function checkIfAnalyticsLoaded() {
  if (window._gat && window._gat._getTrackerByName()) {
    // 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(500, checkIfAnalyticsLoaded();
  }
}    

</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜