Saturday, March 22, 2008

#include or include a file in javascript at runtime

I had written about require or #include in javascript and it works but sometimes you don't want it to be added it using DOM. This function uses DOM incase the body has been loaded or uses document.write to load the file.
function $include(url) 
{
if(document.body)
{
var script = document.createElement("script");
var head = document.getElementsByTagName('head').item(0);
script.src = fileUrl;
head.appendChild(script);
}
else document.write("<script type='text/javascript' src='" + url + "' ></sc" + "ript>");
}


If you look carefully the name of the function is $include. It just makes it stand out other than that you could name it whatever you want. This just makes the code really clean and no more messy html files with 10 script tags to load all the files. It just makes life simpler if you have too many script files to load.

No comments: