Incluye tus Archivos JS y CSS Cuando los necesites
Viernes, Abril 13th, 2007ACTUALIZACIÓN:
Bueno pues no se si a alguno de ustedes les ha surgido el problema de que su sistema esta demasiado cargado al inicio de archivos javascript y css que realmente solo lo utilizan ciertos módulos, pues a mi hace unos meses me surgió ese problema e investigando me puse a trabajar en una libreria que cargara los archivos Javascript mediante el DOM simplemente llamando a un método. La libreria fue basada en este artículo de Sentido Web y en este otro de phpied. El código es el siguiente:
-
var ScriptLoader = {
-
//Método a llamar para cargar el script
-
loadScript: function(file,opt) {
-
-
if(typeof opt!=“object”) opt = {};
-
if(opt.id==undefined) opt.id = “js_”+file;
-
-
id=opt.id;
-
var head = document.getElementsByTagName(‘head’).item(0)
-
var scriptTag = document.getElementById(id);
-
-
//Si no se quiere cache se genera un número aleatorio
-
if(opt.cache==false){
-
var milisegundos = new Date().getTime().toString();
-
if(file.indexOf(“?”)!=-1) file = file+“&”;
-
else file = file+“?”;
-
-
file = file+milisegundos;
-
}
-
-
if(scriptTag) return;
-
-
script = document.createElement(’script’);
-
script.src = file;
-
script.type = ‘text/javascript’;
-
script.id = id;
-
head.appendChild(script);
-
-
//Para IE
-
script.onreadystatechange = function () {
-
if (script.readyState == ‘complete’) {
-
if(typeof opt.oncomplete == “function”) {
-
opt.oncomplete();
-
}
-
}
-
}
-
//Para Firefox
-
script.onload = function () {
-
if(typeof opt.oncomplete == “function”) {
-
opt.oncomplete();
-
}
-
}
-
-
return;
-
},
-
unloadScript: function(id){
-
var head = document.getElementsByTagName(‘head’).item(0)
-
var scriptTag = document.getElementById(id);
-
if(scriptTag) head.removeChild(scriptTag);
-
return;
-
},
-
loadCSS:function(file,opt){
-
if(opt==null) opt = {};
-
if(opt.id==undefined) opt.id = “css_”+file;
-
id=opt.id;
-
-
var head = document.getElementsByTagName(‘head’).item(0)
-
var scriptTag = document.getElementById(id);
-
-
if(scriptTag) return;
-
//Si no se quiere cache se genera un número aleatorio
-
if(opt.cache==false){
-
var milisegundos = new Date().getTime().toString();
-
if(file.indexOf(“?”)!=-1) file = file+“&”;
-
else file = file+“?”;
-
-
file = file+milisegundos;
-
}
-
css = document.createElement(‘link’);
-
css.rel = ’stylesheet’;
-
css.href = file;
-
css.type = ‘text/css’;
-
css.id = id;
-
head.appendChild(css)
-
return;
-
},
-
unloadCSS:function(id){
-
var head = document.getElementsByTagName(‘head’).item(0)
-
var scriptTag = document.getElementById(id);
-
if(scriptTag) head.removeChild(scriptTag);
-
return;
-
}
-
}



