Loading External JavaScript

I came across this excellent post which details what the author purports to be the best way to load external javascript.

The meat of the article is this bit of code:

function loadScript(url, callback){

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

The author suggests loading this function from an external file and then using it to load the remainder of the page’s script. Steve Souders, along with others, weighed in pointing out that this code should be inlined, a point on which I agree. It saves one more request and really doesn’t impact the size of the HTML in which it is placed. An additional point to note (and Nicholas points this out) is that this code should be included at the end of the document in which it appears, rather than the head, as suggested by the code snippet above. Why should it be at the bottom of the body? It allows the DOM elements to be loaded before anything else takes place, even the light weight and out of the way script loader.

Being curious as to what sort of improvements I might see going this route, I incorporated it into a project I’m currently on and WOW! Firefox didn’t really see much of an improvement (3.5; it’s already really fast), but IE (6 and 7) displayed excellent performance gains. An opaque div I use as a loading mask didn’t even make an appearance in IE when, typically, it’s visible on every page load. Not the deepest examination, for sure, but I am impressed with what I’ve seen so far and look forward to using this more in the future!


I discovered today (9.28.2009) that this can trigger a bug in the world’s worst browser – Internet Explorer. According to this article, if a script within an element attempts to modify (either through innerHTML or appendChild) the parent of the element, you can trigger an “Operation Aborted” error in IE 7 (and lower). This bug was supposedly fixed in IE8.

In relation to this issue a colleague offered the ‘defer’ attribute of the ‘script’ tag as an alternative to the method for loading script post HTML render. This doesn’t work because it defers execution of the script, not the loading of the script. The whole point of the method above is to defer the loading so the rendering of the HTML can complete first. ┬áThe reference article can be found here.

Comments are closed.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: