Just wrote a little piece of javascript code that might come in handy for dynamically adding javascript-files without the need to track them (you may repeat as much as you want). It comes in with some nice options, like executing a function on-load and to to force a reload of the javascript-file as well as a reexec of the handler-function.
It’s much superiour to the scriptaculous?load=…, which in my eyes is sort of dumb. I know this is not a beauty either.
I wrote it because I wanted to asynchronously add some javascript-modules without having blocked the loading-process. Something I detected while applying it is that it does not work inside a window’s on-load - it freezes IE7, Safari and Opera, while Firefox not. So be aware. My guess is, that the appending of the javascript to the htmls head causes the on-load to be triggered again, which then obviously leads to a on-load recursive loop.
Okay enough talk, here’s the code then (licence: public domain):
/**
* @url - javascript-file (uri serves too)
* @func - a function to execute after load (no check, I allways use one)
* @reload - reload the file if allready loaded
* @reexec - execute the function in any case
*/
function appendJS(url, func, reload, reexec) {
var head = document.getElementsByTagName("head")[0];
if (!url.match(/https?/))
url = window.location.protocol + ‘//’ + window.location.hostname + ‘/’ + url;
for (var s = 0; s < head.childNodes.length; s++) {
var typ, script = head.childNodes[s], pos;
if (script.tagName && (script.tagName.toLowerCase() == 'script') && (typ = script.src)) {
if (!typ.match(/https?/))
typ = window.location.protocol + '//' + window.location.hostname + '/' + typ;
if (typ == url) {
if (!reload) { if (reexec)
setTimeout(func, 0);
return;
}
head.removeChild(script);
break;
}
}
}
var src;
src = document.createElement('script');
src.onload = function() { func(); };
src.onreadystatechange = function() { if (this.readyState.match(/^(loaded)|(complete)$/)) func(); };
src.type = 'text/javascript';
src.src = url;
head.appendChild(src);
}
And here is one of my use-cases (a automatic acronym-replacer and language-dependent hyphenatizer, loaded side by side with other stuff):
/* prepare-text-filtering (asynchronous, to let the animation run)
* I would liked to have it inside the onload, but it freezes every
* browser except firefox (?)
*/
appendJS('fileadmin/templates/texts.js', function() {
appendJS('fileadmin/templates/acronyms/technical.js', function() {
appendJS('fileadmin/templates/hyphenations/es.js', function() {
/* the loading may delay as so long as we passed reproc allready
* so just do this as prophylactic post-proc
*/
textinit();
textproc(document.getElementById('content'));
});
});
});