Dynamic JavaScript Loading

15 June 2005 ~ blog javascript

I figured out a way to dynamically load JavaScript files at runtime. There are times when you may not always need
to import all of your external JavaScripts, or maybe you are using Ajax to load content into a div and you also need to
import some script that the content needs. Here is the solution and it works in IE and FireFox:

function loadLibrary(path){
    var headElt = document.getElementsByTagName("head").item(0);
    var scriptElt = headElt.appendChild(document.createElement("script"));
    scriptElt.setAttribute("type","text/javascript");
    scriptElt.setAttribute("src",path);
}

Pretty simple, and all you have to do to use it is:

loadLibrary("scripts/myscript.js");

This works for dynamically loading stylesheet too if you add a link element instead of a script element:

function loadStylesheet(path){
    var headElt = document.getElementsByTagName("head").item(0);
    var scriptElt = headElt.appendChild(document.createElement("link"));
    scriptElt.setAttribute("type","text/css");
    scriptElt.setAttribute("rel","stylesheet");
    scriptElt.setAttribute("href",path);
}


Creative Commons License CoffeaElectronica.com content is copyright © 2016 Christopher J. Stehno and available under a Creative Commons Attribution-ShareAlike 4.0 International License.