JavaScript Asynchronous Script Loader

2011 February 11, Updated 2012 May 1

(function() {
    var script = document.createElement('script'),
    	firstScript = document.getElementsByTagName('script')[0],
		loaded;
    script.type = 'text/javascript';
    script.async = true;
    script.onreadystatechange = script.onload = function(e) {
		if (!loaded && (!this.readyState || this.readyState === 'complete' || this.readyState === 'loaded')) {
			this.onreadystatechange = null;
			loaded = 1;
            
	        (function() {
	            // JS fun here
	        }());
        }
    };
    script.src = 'path-to-script.js';
    firstScript.parentNode.insertBefore(script, firstScript);
})();

Update 2012 May 1: Updated the snippet and demo to be a bit better. Old version

Just saw Dustin Diaz's tweet regarding $script.js and thought aha, I was about to throw up yet another one! Mine is just a snippet by comparison and the caveats have not been explored, but it was a start.

After a very quick comparison, where I used the first script element to insert the script, Dustin used the head element. I came to using the first script element while trying to fix an issue with the Google Analytics asychronous script, which had had problems with IE 6 in certain rare circumstances. See Google Analytics Asynchronous Snippet for the Head Element for more about it.

A bit of testing and Dustin's approach also avoids the IE6 problem, so a win all around, hurray!

To clarify, IE6 will die with "Operation Aborted" if there is a singleton base element present in combination with the JavaScript:
document.getElementsByTagName('head')[0].appendChild(el);
but is fine with both:
var head = document.getElementsByTagName("head")[0]; head.insertBefore(el, head.firstChild);

and:
var script = document.getElementsByTagName('script')[0]; script.parentNode.insertBefore(el, script);

Going to check out Dan Webb's loadrunner.js soon, which is looking very fine.

Demo

The demo loads jQuery and appends a paragraph. Compatible with IE 6+, Firefox, Safari, Chrome that I've tested so far.

Reading