Friday, November 16, 2007

javascript include workaround

While i am working on a server side javascript framework, i realize that javascript doesn't support include. that means, you can't directly include another javascript.

If you are write web application, this can be done by

document.write('<script language="javascript" src="' + baseHref
+ 'variables.js"></script>');


However, i want to separate my javascripts into libraries, and called on the server side.
In the end, i write a include function as work around.

usage:


...
var includes = "";
...
include("another.js");
eval(includes);
includes = "";
...






include function:


function include(filename){

length = filename.length;

if (filename.indexOf(".js") < 0) {
filename = filename + ".js";
}
reader = new java.io.BufferedReader(new java.io.FileReader(filename));
while((chunkread = reader.readLine()) != null) {
includes = includes + chunkread + "\n";
}
reader.close();
}

No comments: