Juri Strumpflohner
Juri Strumpflohner Juri is a full stack developer and tech lead with a special passion for the web and frontend development. He creates online videos for Egghead.io, writes articles on his blog and for tech magazines, speaks at conferences and holds training workshops. Juri is also a recognized Google Developer Expert in Web Technologies

HowTo: Include JavaScript file from JavaScript code

1 min read

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>);

Questions? Thoughts? Hit me up on Twitter
comments powered by Disqus