My Ghetto Non-AMD Compliant Dependency Loader

At Cheezburger, we make use of require.js for most of our client side javascript. Recently I had to implement some features that needed to pull lots of 3rd party scripts that were not AMD compliant. The documentation of course told me to put script tags directly in the head of every page, which I have learned recently is a blocking operation (one of the problems that require.js solves cleanly).

So, I took some time and came up with a simple asynchronous dependency loader for this situation.

var dependency_loader = function (dependencies) {

    var callback = undefined;

    var ready = function (cb) {
        callback = cb;
        load_all();
    };

    var loaded = function () {
        if (is_completed() && callback)
            callback();
    };

    var is_completed = function () {
        for (var i = 0; i < dependencies.length; i++) {
            if (!dependencies[i].is_loaded)
                return false;
        }
        return true;
    };

    var load_all = function () {
        for (var i = 0; i < dependencies.length; i++) {
            load_dependency(dependencies[i]);
        }
    };

    var load_dependency = function (dependency) {
        var dependency_element = utils.addScript(dependency);
        $(dependency_element).load(function () {
            dependency.is_loaded = true;
            loaded();
        });
    };

    return {
        ready: ready
    };
};

This object takes an array of dependencies and exposes a ready function that takes a callback to be executed when all dependencies have loaded. Usage looks something like this.

var dependencies = [
            { id: 'foo', http: '//', path: 'cdn.somehwere.com/somedependency1.js', is_loaded: false },
            { id: 'bar', http: '//', path: 'cdn.somehwere.com/somedependency2.js', is_loaded: false }]

 dependency_loader(dependencies).ready(function () {
   doStuff();
 };

Feedback welcome, I am still in a learning phase so if you have suggests or want to point out holes, please do.

Written on June 8, 2012