EFWS home | examples | stevesouders.com
Degrading Script Tag
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 Degrading Script Tags technique, based on a pattern suggested by John Resig. It's an elegant, suprising, and slightly complex pattern. The inlined code's init() function is coupled to the external script by setting script's innerHTML or text property to contain the desired string to evaluate.

if ( -1 != navigator.userAgent.indexOf("Opera") ) {
    domscript.innerHTML = "init();";
}
else {
    domscript.text = "init();";
}

The external script has to be modified to look for this string of code. The external script searches the document's script elements until it finds itself. Then it evaluates the string of code that was added by the coupling technique.

var scripts = document.getElementsByTagName("script");
var cntr = scripts.length;
while ( cntr ) {
    var curScript = scripts[cntr-1];
    if ( -1 != curScript.src.indexOf('menu-degrading.js') ) {
        eval( curScript.innerHTML );
        break;
    }
    cntr--;
}

This technique is flexible - the contract between the external script and the web page is minimal. But it does require that the external script be modified.

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