Why is everyone suggesting the use of document.write()? It seems outdated and not recommended, especially in an XHTML setting.
A better approach would be something like the code snippet below (also available here for reference: https://gist.github.com/767131):
/* Since script loading is dynamic/async, we take
a callback function with our loadScript call
that executes once the script is done downloading/parsing
on the page.
*/
var loadScript = function(src, callbackfn) {
var newScript = document.createElement("script");
newScript.type = "text/javascript";
newScript.setAttribute("async", "true");
newScript.setAttribute("src", src);
if(newScript.readyState) {
newScript.onreadystatechange = function() {
if(/loaded|complete/.test(newScript.readyState)) callbackfn();
}
} else {
newScript.addEventListener("load", callbackfn, false);
}
document.documentElement.firstChild.appendChild(newScript);
}
if(a) {
loadScript("lulz.js", function() { ... });
} else {
loadScript("other_lulz.js", function() { ... });
}
If you have jQuery or a similar library on the page, you can replace my loadScript function with their appropriate function (e.g., $.getScript).