Code: WEDJE Widget loading JavaScript asynchonously

Chapter 6 - Web Page Optimization

WEDJE creates a cross-platform, cross-browser defer by using the document object model (DOM) to append a div, create a script element, and then append the script element to the div, all with JavaScript. An example of the technique follows:

<script type="text/javascript"> // create div below
(function( ){document.write('<div id="wedje_div_example">Loading widget...<\/div>');
    s=document.createElement('script'); // create script element
    s.type="text/javascript"; // assign script to script element
    s.src="http://www.example.com/scripts/widget.js";
    // assign script s to div element
    setTimeout("document.getElementById('wedje_div_example').appendChild(s)",1);})( )
</script>

When these elements are linked together in this way, browsers appear to decouple the loading and execution of the attached JavaScript, making widget execution asynchronous! Here is the matching external JavaScript file, widget.js, which grabs the div we created earlier and loads an image:

document.getElementById('wedje_div_example').innerHTML+='<img src="http://www.
example.com/images/example.gif" width="60" height="60" />';