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";
script.src = src;
And then call it from within your JavaScript code with

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() {
And then by calling it similarly as in the loadScript function

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