Implementing custom solutions to track pages, events and other with Google Analytics, I would like to check if the ga.js
library has already been included to avoid a double include, since I am working in an environment with multiple stakeholders which also use Google Analytics, and overlapping is a possibility.
At first, I thought to cycle all the current scripts, looking for the src
attribute:
// load the Google Analytics library only if it has not been already loaded:
var gaScripts = 0; // number of ga.js scripts in the current document
var scripts = document.getElementsByTagName('script');
for (var i in scripts) {
// go through all the scripts:
if (typeof(scripts[i].src) !== 'undefined' && scripts[i].src.split('?')[0].match(/ga\.js$/)) {
// update the counter if ga.js has been found:
gaScripts++;
}
}
if (gaScripts === 0) {
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
// update the counter:
gaScripts++;
} else if (gaScripts > 1) {
// the ga.js library has been loaded more than once, log this error:
if (window.console) {
console.log('Warning: the ga.js script has been included ' + gaScripts + ' times in the page');
}
}
It works, and also logs potential errors of multiple includes.
Then I thought something smarter, by checking the object prototype of the _gaq
stack:
with (window) {
if (_gaq instanceof Array) {
// not loaded, so include it...
} else {
// it's been included
}
}
When the _gaq
object is still uninitialized by the ga.js
library, it is a simple array, so the first condition is true.
When it is initialized, it is overwritten as an object, which in no more instance of the Array primitive object.
Drawbacks
I am wondering about the window.onload
epic problem: implementing the solutions as synchronous code (evaluated in the point it is located), if the ga.js
library has been included but not yet loaded in the DOM because asynchronously called, it would anyway incur in a double include.
So the DOMContentLoaded
event should be triggered to invoke one of the two solutions in that while.
I searched the web for similar questions around this topic, but the official GA documentation lacks of information about it, neither results on popular resources seems to treat it.
Another question I posed to me is wether a double include is an issue: from a pure technical perspective, I thought Google Analytics could forecast this kind of user error and manage it, as in some case it does (does somebody know if it is so?). But from a user perspective, the time for a second useless HTTP request is annoying and hopefully to be avoided.
Did someone face this problem or have some suggestion?