I’ve been messing with javascript pretty heavily for a couple of years now, and one thing that has always bothered me is I can’t include script with javascript. I previously used dom to create the script tags, and for css the link tags. The problem with this is that, the new script you create isn’t parsed until after your current script finishes. I had a thought though and here is what I came up with.
The Function
function include(jsFileLocation) {
if(window.XMLHttpRequest) {
var req = new XMLHttpRequest();
} else {
var req = new ActiveXObject(”Microsoft.XMLHTTP”);
}
req.open(”GET”, jsFileLocation,false);
req.onreadystatechange = function() {
if (req.readyState == 4) {
window.eval(req.responseText);
}
}
req.send(null);
}
Example Included File (speaker.js)
var speaker = {
say : function(what)
{
alert(”Speaker Says ‘” + what + “‘”);
}
}
Example Usage
include(’speaker.js’);
speaker.say(”Hello World”);
Ok so as you can see we are just using basic JSON principles loading the javascript in and running window.eval instead of just eval, reason for this is you need to evaluate the javascript on the top level otherwise your other toplevel code won’t be able to use it. Also you might wonder how we can just run the code immediately after sending the ajax request. The trick is the third parameter to open(). Its a boolean used to set weither the ajax should be asynchronous or not. In our case we want it to not be. That way, javascript holds further code execution untill the included file is loaded and parsed.
By the way, I’ve tested this so far with Internet Explorer, Firefox, Safari, Chrome, and Opera.