I find the JS interpreter demo that the MochiKit folks put out to be quite useful. It makes it easy to do little JS experiments from any web browser. Many times, however, I’d like to import some external JS libraries that I’ve stored elsewhere on the web into that interpreter, and there doesn’t seem to be a built-in way to do that. A little googling turned up a nearly ready-made bit of code that can be copy-and-pasted into the interpreter to solve the problem.
The following code, if executed from the lower text area of the MochiKit interpreter, will define a function that can be subsequently used to import other JS files. It is based on this post in the MochiKit Trac system. The ‘test’ parameter may be omitted in IE or FF; its purpose is described here.
loadScript = function (url, test) {
var d = new MochiKit.Async.Deferred();
var head = document.getElementsByTagName('head')[0];
var script = MochiKit.DOM.createDOM('script', {type:'text/javascript', charset:'iso-8859-1', src:url});
var cbTimer = undefined;
var callback = function() {
script.onload = null;
script.onreadystatechange = null;
if (cbTimer) { clearInterval(cbTimer); }
d.callback();
};
if (test)
{
var spinner = function () {
var call = false;
try { call = test(); }
catch (e) {}
if (call) { callback(); }
};
cbTimer = setInterval(spinner, 100);
}
script.onload = callback;
script.onreadystatechange = function() {
if (script.readyState == 'loaded' || script.readyState == 'complete') {
callback();
}
};
head.appendChild(script);
writeln('Loading ' + url + ' ... please wait ...');
d.addCallback(function () { writeln(url + ' loaded'); });
blockOn(d);
};
Here’s an example of the code in action, testing a JS Base64 codec:
It’s a small thing, but I find it useful.