Checking if Google Analytics library has already been included
===

Implementing custom solutions to track pages, events and other with Google Analytics, I would like to check if the <code>ga.js</code> library has already been included to avoid a double include, since I am working in an environment with multiple stakeholders which also use tracking.

At first, I thought to cycle all the current scripts, looking for the <code>src</code> attribute:

	// load the Google Analytics library only if it has not been already loaded:
	var gaScripts = 0;
	var scripts = document.getElementsByTagName('script');
	
	for (var i in scripts) {
		if (typeof(scripts[i].src) !== 'undefined' && scripts[i].src.split('?')[0].match(/ga\.js$/)) {
			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);
		})();
	} else if (gaScripts > 1) {
		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 <code>_gaq</code> stack:

	with (window) {
		if (_gaq instanceof Array) {
			// not loaded, so include it...
		} else {
			// it's been included
		}
	}

When the <code>_gaq</code> object is still uninitialized by the <code>ga.js</code> 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 <code>window.onload</code> epic problem: implementing the solutions as synchronous code (evaluated in the point it is located), if the <code>ga.js</code> library has been included but not yet loaded in the DOM because asynchronously called, it would anyway incur in a double include.
So the <code>DOMContentLoaded</code> 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.

Did someone face this problem or have some suggestion?
