JavaScript - DOM - Dynamic Script Loading


How can we dynamically load a script?

var script = document.createElement("script");
script.type = "text/javascript";
script.src = "file.js";

There are two things to note about this code. First, the download doesn’t actually begin until the script node is added to the document. This is different from dynamically creating an <img> element, for which assigning the src automatically begins the download even before the node is added to the document. The second thing to note is that you can add the script node either to the <head> or <body>; it really doesn’t matter. That’s all it takes to dynamically load a JavaScript file without blocking the page.

How can we be notified when a dynamic script is loaded?

You may also want to be notified when the JavaScript file is fully downloaded and executed, and that’s where things get a bit tricky.

function loadScript(url, callback){
    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
    } else {  //Others
        script.onload = function(){

    script.src = url;

To use this, just pass in the URL to retrieve and a function to call once it’s loaded:




Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License