Couple XHR Eval

Examples ▼
Was the script loaded without blocking?
Was execution order preserved?
 
 
 

This page contains an external script and some inlined code. The external script is loaded asynchronously (using the Script DOM Element technique). The inlined code's init function calls scriptAFunc, 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 scripts are loaded via XMLHttpRequest. (The entire implementation of this technique is too long to show in this page. Look at the source of this document to see the code.) When the response is received, it's evaluated using eval.

eval(xhrObj.responseText);
This technique loads scripts A and B in parallel, but it doesn't execute them in the order they were originally specified. The order the scripts are listed in the page is A, B, and the inline script. But you can see from the times displayed above that they actually execute in the opposite order: inline script, B (because it returns more quickly), and finally A. This produces an undefined symbol error when the inline script in the page tries to reference a symbol from script A, "scriptAFunc".