Tag: loadfile

Javascript/css loader

Coding

If you are a webdev you probably know that, sooner or later, you will need a way to load css and javascript asynchronously when you need them, and maybe track what you have loaded such that you don’t reload the same resources once again when you need them in other component.

ExtJs has that feature: the very well designed Ext.Loader can load arbitrary javascript files just looking on the configured paths of the different resources. On the other side of the most common libraries, Jquery has the $.getScript() function that does exactly the same thing, in a more dummy way. It just loads the javascript in the path passed as argument.

None of them are able to handle css, tho viagrafromuk.com. So I wrote a small, library independent function to load a javascript or css dynamically. Here is the code:

var loadfile = (function(){
    //our hash table to keep record of already loaded files
    var loadedfiles = {};
    //TODO add callback
    return function(filenames, callback){

        if(!(filenames instanceof Array)){
            if(typeof(filenames) == 'string'){
                filenames = [filenames];
            }else{
                throw 'filenames is not an Array or a string';
            }
        }

        var map = {
            js: function(filename){
                var tag=document.createElement('script');
                tag.setAttribute("type","text/javascript");
                tag.setAttribute("src", filename);
                return tag;
            },
            css: function(filename){
                var tag=document.createElement("link");
                tag.setAttribute("rel", "stylesheet");
                tag.setAttribute("type", "text/css");
                tag.setAttribute("href", filename);
                return tag;
            }
        },i,length,type,tag,filename, ext;

        length = filenames.length;
        if(length>0){
            for(i=0; i<length; i++){
                filename = filenames[i];

                if(loadedfiles[filename])
                    //continue if we have already loaded this file
                    continue;

                type = filename.lastIndexOf('.');

                if(type === -1)
                    throw filename+' is not a valid filename with extension';

                ext = filename.slice(type+1);

                //create correct tag
                tag = map[ext](filename);

                //append to head
                document.getElementsByTagName("head")[0].appendChild(tag);

                //update hash table for files we've already loaded
                loadedfiles[filename] = true;

                //call callback
                if(callback && typeof(callback) === 'function')
                    callback(filename);
            }
        }
    };
})();

The loadfile function uses closure to store an hashmap of the loaded file and accepts an single string or an array of strings representing the paths to load. It also accepts an optional callback function that will be called if and when the script has been loaded into the page.

Feel free to use it as you wish. And if you like, give me some credit!

%d bloggers like this: