JavaScript Asynchronous Script Loader

Created 2011 February 11. Last modified 2011 February 19

<script type="text/javascript">
//<![CDATA[

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

//]]>
</script>

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