EFWS home | examples | stevesouders.com
Script Onload
Examples ▼
Was the script loaded without blocking?
Was execution order preserved?

This page contains an external script and some inlined code that depends on the external script. The external script, menu.js, is loaded asynchronously. The inlined code's init function calls EFWS.Menu.createMenu(), a function defined in the external script. Because of this dependency, the inlined code must be coupled with the external script so that the execution order is preserved: the external script is loaded, parsed, and executed before the inlined code.

In this example, the external script and inlined code are coupled using the Script Onload technique. This is best alternative to use that balances ease-of-use and performance. The init() function is tied to the script's onload (or onreadstatechange) event.

domscript.onload = function() { 
    if ( ! domscript.onloadDone ) {
        domscript.onloadDone = true; 
        init(); 
    }
};
domscript.onreadystatechange = function() { 
    if ( ( "loaded" === domscript.readyState || "complete" === domscript.readyState ) && ! domscript.onloadDone ) {
        domscript.onloadDone = true; 
        init();
    }
}

This works across browsers. It causes the inlined code to be invoked as soon as possible after the external script is done loading. It has minimal overhead.

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