EFWS home | examples | stevesouders.com
Script DOM Element and Doc Write
Examples ▼
Was the script loaded without blocking?
Was execution order preserved?

This page contains two external scripts (menu.js and menutier.js) and some inlined code. The scripts have cascading dependencies: the inlined script depends on menutier.js, and menutier.js depends on menu.js. Because of these dependencies, if we load the scripts asynchronously, we have to preserve the execution order of the external scripts as well as the inlined script.

In this example, the external scripts are loaded from a domain that is different from the main page. Therefore, the Managed XHR technique can't be used. Instead, the Script DOM Element approach is used in Firefox and Opera, and document.write Script Tag is used in other browsers. The init function is provided as the callback for when menutier.js is done loading.

if ( -1 != navigator.userAgent.indexOf('Firefox') || -1 != navigator.userAgent.indexOf('Opera') ) {
    EFWS.Script.loadScriptDomElement("http://souders.org/efws/menu.js");
    EFWS.Script.loadScriptDomElement("http://souders.org/efws/menutier.js", init);
}
else {
    EFWS.Script.loadScriptDocWrite("http://souders.org/efws/menu.js");
    EFWS.Script.loadScriptDocWrite("http://souders.org/efws/menutier.js", init);
}

This isn't optimal; document.write Script Tag has many drawbacks. But it is the only viable technique when multiple interdependent scripts are loaded asynchronously. Despite it's drawbacks, it loads scripts without blocking in most browsers. Whenever possible, it's better to combine your scripts into a single script, and load them using the simpler "Single Script" techniques.

home | contact SteveBlackbuck AntelopeThis is the companion website for Even Faster Web Sites by Steve Souders.