Samuel Sjöberg's weblog

Skip to navigation

On Demand Javascript

In a project I'm working I need to be able to dynamically load small javascript apps. A dynamically created menu should be able to launch the different apps it displays. The menu can be loaded with data sent as JSON from the server side and. Since the menu is dynamic, it isn't possible (and shouldn't be necessary) to load all scripts in advance.

The solution is to load scripts on demand. On demand javascript is neat, but requires that you somehow wait until the script has loaded before you execute it. Multiple solutions for this exists and many seems to use some sort of callback to solve the problem.

My approach is a bit different, yet simple. All apps are loaded through the same object. That object is also responsible for initiating the just loaded app and unload the previous one. This allows me to control the loading process with a simple timer.

var sas = {}; // namespace
sas.app = new function() {

    var current = null;
    var pollInterval;
    var polled;

    function init(name) {
        current = sas.app[name];
        current.init();
    }

    function demand(name) {
        var script = document.createElement('script');
        script.setAttribute('type', 'text/javascript');
        script.setAttribute('src', sas.app.path + name + '.js');
        document.getElementsByTagName('head')[0].appendChild(script);

        polled = name;
        pollInterval = window.setInterval(poll, 100);
    }

    function poll() {
        if (typeof sas.app[polled] != 'undefined') {
            window.clearInterval(pollInterval);
            init(polled);
        }
    }

    return {
        path : '',

        load : function(name) {
            if (current != null) {
                current.destroy();
            }

            if (typeof this[name] == 'undefined') {
                demand(name);
            } else {
                init(name);
            }
        }
    }
}

This implementation makes the following assumptions about the loaded code.

I wan't to emphasis that these conditions apply to the current implementation, but I can't see any reason as to why it shouldn't be possible to write a solution that doesn't require all of these conditions to be met.

I've put up a small proof of concept from where the snipped above is copied. Note that the menu actually is a pluggable app in the same way that the dynamically loaded scripts are. I think that's pretty neat.

Pages linking to this entry

Pingback is enabled on all archived entries. Read more about pingback in the Pingback 1.0 Specification.

About this post

Created 14th September 2008 22:58 CET. Filed under Javascript and DOM.

0 Comments
0 Pingbacks