Wednesday, March 12, 2008

Javascript Import / Include

We can load JS files in the HEAD part of a HTML document, but have you ever needed to load a JS file from another script?

you can use this code:

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'snip.js';
document.getElementsByTagName('head')[0].appendChild(script);



And if you don't want to write it again and again, and prefer to prevent loading a JS file more than one time you can use this clean function:


function $import(path){
var
i, base, src = "grid.js", scripts = document.getElementsByTagName("script");
for (
i=0; i<scripts.length; i++){if (scripts[i].src.match(src)){ base = scripts[i].src.replace(src, "");break;}}
document.write("<" + "script src=\"" + base + path + "\">+ "script>");
}


// example

$import("controls/grid.js");
$import("http/request.js");

But I strongly recommend you to use the AjaxCSSJS calss instead.