miércoles 23 de noviembre de 2011

Load javascript or css dynamically in javascript

If for some reason you need to programatically load some javascript or css stylesheet in the document, here is some code that helped me and seems to work fine in most browsers. Hope that helps somebody




/**
* loads javascript file or css stylesheet in current document.
* Usage Examples:
* loadFile("www.server.com/file1.js", "js", function(){
* alert("file1.js loaded!");
* });
* @param name : the url of the resource to load. I think there is no cross site problems here.
* @param type : "js" or "css". if "js" then a new javascript script will be loaded
* @param listener an optional function that will be called when loading of the resource is ready.
* @author: sgurin
*/
_loadF : function(name, type, listener){
var el=null;
if (type=="js"){
el=document.createElement("script");
el.setAttribute("type","text/javascript");
if(listener) {
el.onreadystatechange = function () {
if (this.readyState == 'complete') listener();
};
el.onload=listener;
}
el.setAttribute("src", name);
}
else if (type=="css"){
el=document.createElement("link");
el.setAttribute("rel", "stylesheet");
el.setAttribute("type", "text/css");
el.setAttribute("href", name);
}
document.body.appendChild(el);
}