It’s More Than Where You Load JavaScript, but How

Well I know that JavaScript blocks anything else from downloading on the page. My strategy to lessen this effect has been to move JavaScript to the bottom of the page. After reading 12 Steps to Faster Web Pages with Visual Round Trip Analyzer, I have to question this strategy. It describes a technique for using JavaScript to write the external script tags.

function AsyncLoad()
{
    var l = arguments.length;

    for (var i=0;i<l;i++)
    {
        document.write("<script src='" + arguments[i] + "'></" + "script>");
    }
}

AsyncLoad("file1.js", "file2.js", "file3.js");

The article states that although moving external scripts to the bottom reduces their blocking effect, it doesn’t take advantage of the bandwidth available to get everything downloaded as soon as possible. So, loading files with a document.write allows them to be loaded outside of the JavaScript engine, hence no blocking by JavaScript. How is this so?

Well let’s take a trip deep into geek land and check into how browsers actually interact with external scripts. Reading through this Mozilla bug report (https://bugzilla.mozilla.org/show_bug.cgi?id=364315) and a few other sites, when the browser encounters a script tag that references an external script it will download the script. It will not allow parallel downloading of other assets until the script is done downloading and parsing. Don’t take this as gospel, because I haven’t looked at browser source code or anything. I am just interpreting what I have read from multiple sources. This bug report also suggest that the browser vendors are already attacking the blocking behavior so the technique I am describing here won’t be needed in newer browsers.

So, although async JavaScript loading doesn’t address the problem of HTTP requests, but it prevents those pesky JavaScript blockers from causing a traffic jam, allows other elements to download in parallel, and efficiently uses bandwidth.

Well I’m off to do some testing. If you haven’t played around with Visual Round Trip Analyzer, I will be blogging about it soon (if I have the time).

I hope you found this useful.

Leave a Reply

    RSS Subscribe to comment feed.