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 init() function is include inside the external script's SCRIPT tags.
<script src="menu-degrading.js" type="text/javascript"> init(); </script>
Browsers don't currently support such a syntax, so the external script has to be modified to look for this code. The external script searches the document's script elements until it finds itself. Then it evaluates the string of code inside the SCRIPT tags.
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 doesn't avoid the script's blocking delays. We can combine it with an asynchronous script loading technique and get the benefits of this coupling technique as well as non-blocking scripts. You can see that in the Degrading Script Tag example.