Loading scripts on demand

It stumbled me: Why do I load AJS and GreyBox on amix.dk when they are only used for login and posting comments. Why not load them on demand? I would save around 40 KB for every user that visits my site. This would mean I would save bandwidth and the site would be much faster to load.

The example

My quest began and after 20 min I had a solution that worked in every modern browser! Here is how to use the function:

function needsScripts(arg1) {
  var div = AJS.DIV();
  alert(div);
}
needsScripts = onDemand(needsScripts, ['AJS.js', 'greybox.js']);
needsScripts("Cow is mad");

needsScripts is a function that is dependent on AJS.js and greybox.js. We use another function onDemand to decorate needsScripts. When needsScripts is called AJS.js and greybox.js will be loaded dynamically.

The implementation

Here is the implementation of onDemand (no library is needed). Caution: Using onload on a script tag does not work in Internet Exploder or Safari, that's why you have to place script_loaded = true in any script that should be loaded dynamically, I know this can be a limitation, but it's the only easy way to support multiple browsers.

var script_loaded = true;
var load_timeout = 10000; //10 sec
function onDemand(fn, srcs) {
  return function() {
    var args = arguments;
    var current_time = 0;
    var current_script;
    var load_script = function() {
      if(current_time >= load_timeout) {
        alert("Could not load JavaScript: " + current_script);
        return;
      }
      if(script_loaded == true) {
        if(srcs.length != 0) {
          script_loaded = false;
          current_time = 0;
          var head = document.getElementsByTagName("head")[0];
          var script = document.createElement("script");
          current_script = srcs.shift()
          script.src = current_script;
          head.appendChild(script);
        }
        else {
          return fn.apply(window, args);
        }
      }
      current_time += 25;
      window.setTimeout(load_script, 25);
    }
    load_script();
    return false;
  }
}

The conclusion

If you want to save bandwidth then this is a very nifty trick. I have already patched Skeletonz so it uses lazy loading of scripts when it isn't in edit mode.

AJAX and comet · Code · JavaScript · Skeletonz 8. Sep 2006
2 comments so far

Hi, I tryed to cache alredy loaded scripts, but doenst work.
Can you add caching support on you script?

Thank you for you script, I think that this is the only one "googlabe" script, that I found on the Internet.

See Ajile [ http://ajile.iskitz.com/ ]. It supports easy loading without limitations and provides namespace and import support.

Post a comment
Commenting on this post has expired.
© 2000-2009 amix. Powered by Skeletonz.