Dynamic, cross-browser script loading

I want to add that if you don't support IE7 and below, you don't need onreadystatechange stuff. Source: quircksmode.org

Simplified and working code from original answer:

function loadScript(src, callback) {    
    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.src = src;
    s.async = false;
    if(callback) {
        s.onload = callback;     
    }
    document.body.appendChild(s);
}

You can use a script loader like head.js. It has its own load callback and it will decrease load time too.


From the headjs code: (slightly modified to be more portable)

function scriptTag(src, callback) {

    var s = document.createElement('script');
    s.type = 'text/' + (src.type || 'javascript');
    s.src = src.src || src;
    s.async = false;

    s.onreadystatechange = s.onload = function () {

        var state = s.readyState;

        if (!callback.done && (!state || /loaded|complete/.test(state))) {
            callback.done = true;
            callback();
        }
    };

    // use body if available. more safe in IE
    (document.body || head).appendChild(s);
}