I Am Not Myself


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;

        var loaded = function () {
            if (is_completed() && 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++) {

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

        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 () {

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: