Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have to use a local analytics.js that I serve from my server. I just want to use the local version if necessary - so is there a solution for checking if the call for analytics.js has failed?

I thought about checking it with a global window.onerror, but I don't think a failed call for an external file causes an error. I've tried checking if ga() is available, but it is even if analytics.js isn't loaded.

Any ideas? If you are wondering, not all users of this site has internet access, that's why I'm serving a local version. There is more things happening in this case, like adding a sendHitTask to redirect the answer from analytics.js to the local server.

EDIT A solution where you check if the user has Internet access would also be OK. But I have not found any solution for this either that works on all modern browsers.

See Question&Answers more detail:os

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

1 Answer

There's a function to track if the library has loaded. From the docs:

ga(function(tracker) {
   var defaultPage = tracker.get('page');
});

The passed in function is executed when the library is loaded, so you could set a variable to keep track of whether or not it has loaded. You'd have to put it on some sort of timer to decide when you want to consider it failed:

var loaded = false;
ga(function() {
   loaded = true;
});

// after one second do something if the library hasn't loaded
setTimeout(function(){
    if (!loaded){
        //do something
    }
},1000);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...