HowTo: Include JavaScript file from JavaScript code

Recently a colleague asked me on how to add a JavaScript file reference to an HTML document from within JavaScript code. It's actually quite easy. All you need is to create the appropriate element and attach it to the HTML document's dom structure on the appropriate position, i.e. the head element. The following JavaScript does the job.
function loadScript(src) {
var script = document.createElement("script");
script.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(script);
script.src = src;
}
And then call it from within your JavaScript code with
loadScript('http://someurl.com/test.js');

Similarly you may want to attach a JavaScript function programmatically to the HTML body's onLoad event. This can be achieved with the following function
function addLoadEvent(func) {
var old = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
old();
func();
}
}
}
And then by calling it similarly as in the loadScript function
addLoadEvent(<someJavaScriptFunction>);
Kindle

Comments

0

Your ad here?