Call (877) SITE-OPT (748-3678)

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
    // assign script s to div element
    setTimeout("document.getElementById('wedje_div_example').appendChild(s)",1);})( )

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." width="60" height="60" />';
Copyright © 2002-2018 Website Optimization, LLC. All Rights Reserved - Free website speed test - Privacy Policy
Last modified: February 19, 2009.

Follow us on: Twitter, Google+, Facebook, Linked In