Pages

Thursday, March 6, 2014

JS: Javascript Class/File Dependency Handler

Here is the dependency class based on singleton design pattern in javascript. This class can handle all the javascript file dependencies from inside the script. That means you don't need to include the file in the script tag under html head. In fact, you can use it just like import/include/require statements in other language.

It's usage is very simple. You just have to declare the class object which would be global since it is a singleton class, then call the import method to include the javascript file on which current file or method is dependent; then listen for the success event on which you can use that imported class/file method as specified.

/* 
@file CDependency.js
@author Abhishek Kumar
@email abhishek.kumar@intigate.com
*/

function CDependency() {
    if (arguments.callee._singletonInstance) {
        return arguments.callee._singletonInstance;
    }
    arguments.callee._singletonInstance = this;

    var list = [];

    // jquery based method
    var jqload = function (filepath, callback) {
        if (list.indexOf(filepath) < 0) {
            list.push(filepath);
            $.getScript(filepath, callback);
        } else {
            callback();
        }
    };

    this.require = function (filepath, callback) {
        jqload(filepath, callback);
    };

    this.requires = function (filepaths, callback) {
        var counter = 0;
        var loadJs = function () {
            if (counter < filepaths.length) {
                jqload(filepaths[counter++], loadJs);
            } else {
                callback();
            }
        };
        loadJs();
    }

    // basic javascript method
    this.load = function (filepath, callback) {
        if (list.indexOf(filepath) < 0) {
            list.push(filepath);
            var head = document.getElementsByTagName('head')[0];
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = filepath;
            script.onreadystatechange = callback;
            script.onload = callback;
            head.appendChild(script);
        }
    }
}
/*
// Usage
oDependency = new CDependency();
oDependency.import('scripts/cache.js', function () {
    console.log('yuppie');
});
*/

No comments:

Post a Comment