Asynchronous Script Loading
Bernard Lange
@gustaff_weldon
Bernard Lange
@gustaff_weldon
<script src="jquery.js"></script> <script src="jquery-plugin-1.js"></script> .... <script src="jquery-plugin-n.js"></script> <script src="my-script.js"></script>
the average top ten U.S. web site contains ~250K of JavaScript. But executes 25% of it before the onload event.Souders, 2008
<iframe src='A.html'></iframe>
// access iframe from main page
window.frames[0].someMethodInScript();
// access main page from iframe
parent.document.createElement('div');
slowest and most expensive DOM element to create
eval(xhrObj.responseText);
document.head.appendChild(script); script.text = xhrObj.responseText;
<script defer src="script.js"></script>
execute after the document has been parsed
var script = document.createElement("script");
script.src = url;
document.head.appendChild(script);
<script async src="script.js"></script>
execute asynchronously when script is available
<script src="slow.js"></script> ... <img src="HTML5_Logo.png"/>
<script async src="slow.js"></script> ... <img src="HTML5_Logo.png"/>

type hack
var s = doc.createElement('script');
s.type = 'text/cache';
s.src = url;image/object hack
if (isIE) {
new Image().src = scriptUrl;
}
o = document.createElement('object');
o.data = scriptUrl;
to make script-inserted external scripts execute in their insertion order
var script = document.createElement("script");
script.async = false;
script.src = url;
document.head.appendChild(script);
var script = document.createElement("script");
script.src = url;
document.head.appendChild(script);
var script = document.createElement("script");
script.async = false;
script.src = url;
document.head.appendChild(script);
No single technique warranties order execution in all browsers
<script src="framework.js"></script> <script src="plugin.framework.js"></script> <script src="myplugin.framework.js"></script> <script> framework.init(); myplugin.doSomething(); </script>
$LAB.script("framework.js")
.wait()
.script("plugin.framework.js")
.script("myplugin.framework.js")
.wait(function(){
framework.init();
myplugin.doSomething();
});
format to provide a solution for modular JavaScript that developers can use today
define('myModule', ['math', 'graph'],
function ( math, graph ) {
var pub = {
plot: function(x, y){
var coords = math.randomGrid(x,y);
return graph.drawPie(coords);
}
};
return pub;
};
});
require(['foo', 'bar'], function ( foo, bar ) {
// rest of your code here
foo.doSomething();
});
//Dojo 1.7 (AMD)
require(["dojo/ready","dojo/fx"], function(ready,fx) {
ready(function(){
require(["dijit/form/Button","dojo/_base/window"], function(btn,win) {
ready(function(){
new dijit.form.Button({}).placeAt(win.body());
});
});
});
});
Dojo 1.7, Mootols 2.0, jQuery 1.7 - AMD compliant
@gustaff_weldon