Simplifying your Headers
January 4th, 2007 -
Yesterday I was asked by Yannick if it was possible to include JavaScript files within other JavaScript files. Now, from a computer science perspective, anything is possible, but JavaScript doesn’t allow a simple include “myJSfile.js”;. So what is one to do?
DOM to the Rescue!
The DOM is a beautiful thing. There is so much we can do with it, and it is the key to solve this little problem.
function include_js(jsFile) {
var jscript = document.createElement("script");
jscript.type = "text/javascript";
jscript.src = jsFile;
document.getElementsByTagName('head')[0].appendChild(jscript);
}
The above code will take the file name (myjsfile.js) as the parameter passed to it and create a script element with the necessary information and place it within the head of your document.
To use it, one could simply take that function, place it into a JS file, then below the function add what files they want to include. Ex:
...put the actual include_js function here...
include_js("jquery.js");
include_js("thickbox.js");
include_js("validate.js");
Wrap the function and function calls into a JS file and include that JS file in the header of your XHTML file.
There you have it, a simple way to include all your JS files within a JS file itself.
Tags: development
Comments
Robert
January 6th, 2007
Nic: I haven’t seen this with simple/small scripts. But after testing with several scripts (prototype, scriptaculous), they don’t load completely. I did, however, find that Dojo has a require method built in that will load all javascript or whatever.
Looking at the source, one could built a small library (Dojo is huge) that would give the same functionality as require does for Dojo.
Mislav
January 8th, 2007
Dynamic SCRIPT element is not cross-browser if generated with DOM. I think for Safari you have to use document.write or innerHTML…
Dr. Nic: the bootstrap file (illustrated above) can initiate polling that stops as soon as the certain object (namespace) is found.
Commenting has been turned off.
Dr Nic
January 6th, 2007
It seems that loading code via <script src=’...’> is an non-blocking operation – your original code is not blocked whilst it waits for the script to be loaded. Have you seen this? How have you made your code wait for the loaded scripts to complete?