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.
There's a function to track if the library has loaded. From the docs https://developers.google.com/analytics/devguides/collection/analyticsjs/command-queue-reference#ready-callback:
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);
instead of waiting for a callback, you can easily get it with
if(window.ga && ga.loaded) {
// yeps... it is loaded!
}
you can easily see this in the Firefox documentation
same trick can be applied if you want to see if the tracker is blocked (by any plugin for example)
if(window.ga && ga.q) {
// yeps... blocked! >:o
}
A particularly elegant solution would be to use RequireJS and leverage its support for fallback paths. I do this on my site to load a stub version of analytics.js
if loading GA fails because the visitor uses a privacy tool blocking the request:
http://veithen.github.io/2015/02/14/requirejs-google-analytics.html
Your use case is similar, except that you want to fallback to a complete local copy. You also probably don't want to change all calls to GA as described in that article. If that's the case then you could use a hybrid approach where you only use RequireJS to load analytics.js
(Google's version or the local copy), without changing any other code.
Setting this up would involve the following steps:
Add RequireJS to your site and configure it as follows:
require.config({
paths: {
"ga": [
"//www.google-analytics.com/analytics",
"local-copy-of-analytics"
]
}
});
Use the alternative version of the tracking code, but replace <script async src='//www.google-analytics.com/analytics.js'></script>
with the following JavaScript code:
require(["ga"]);