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

Code: Improvements to JavaScript on demand

Chapter 9 - Advanced Web Performance Optimization

You can make a few enhancements to the script in the preceding section. First, to avoid caching, you can add a random seed to the script name, like so:

function include_jsNoCache {
    var ms = new Date().getTime( ).toString( );
    var seed = "?" + ms;
    include_js(src + seed);
}

This function will import the script with a random query parameter to avoid caching. Unfortunately, Safari doesn't spawn an onload event with the preceding code.

It turns out that setting the onload and src attributes before loading the script will spawn an onload event in Safari. The preceding script also does no housecleaning to conserve memory. Once a script has been added to the DOM and used, it can be removed to save memory. Here is the revised script:

include_js = (function( ){
    var uid = 0;
    var remove = function(id){
    var head = document.getElementsByTagName('head')[0];
    head.removeChild( document.getElementById('jsInclude_'+id) );
};
return function(file,callback){
    var callback;
    var id = ++uid;
    var head = document.getElementsByTagName('head')[0];
    var js = document.createElement('script');
    js.setAttribute('type','text/javascript');
    js.setAttribute('src',file);
    js.setAttribute('id','jsInclude_'+uid);
    if( document.all )
        js.onreadystatechange = function( ){
        if(js.readyState == "complete"){ callback(id);remove(id); }
        };
        else
            js.onload = function( ){
                callback(id); remove(id);
            };
        head.appendChild(js);
        return uid;
    };
})( );

For more details on this technique by Stoyan Stefanov, see http://www.phpied.com/javascript-include-ready-onload/.

Copyright © 2002-2017 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