How to dynamically load a JS file in JavaScript

Typically, we load a JavaScript file using the script tag:

<script src="https://www.mywebsite.com/test.js"></script>

Dynamic loading

In some situations, we want to load third-party script fileslike Google Analytics and Google Ads dynamically in JavaScript.

Those files can be loaded asynchronously in JavaScript.

To load a JavaScript file dynamically:

  • Create a script element.
  • Set the src, async, and type attributes.
  • Append the script element to the body.
  • Check if the file loaded or not in the load event.

Create a script element

First, we need to create a script element as given below:

let scriptEle = document.createElement("script");

Set the src, async, and type attributes.

  • src: the file path
  • type: file type - "text/javascript"
  • async: if we set async to false, then the file will be loaded and executed first before proceeding to the next action.
scriptEle.setAttribute("src", "https://www.mywebsite.com/test.js");

Append the script element

We have two options to append script element:

  • Append it to the <head> section if we want it to load early during page initialization.

  • Append it to the <body> element if we want it to load after other content has loaded.

document.head.appendChild(scriptEle);

// OR append to the body (after other content)

document.body.appendChild(scriptEle);

Note: If we want to append the script dynamically, consider the appropriate placement of the script element. If we intend to append the script to the <body> element, ensure that our HTML document structure supports this. Scripts appended to the <body> should typically manipulate or interact with elements within the body content. Placing scripts in the <head> section can lead to timing issues with DOM manipulation if they attempt to interact with <body> elements before the <body> content has fully loaded.

Check the load event

Next, check either file is loaded successfully or not.

scriptEle.addEventListener("load", () => {
    console.log("File loaded")
});

scriptEle.addEventListener("error", (ev) => {
    console.log("Error on loading file", ev);
});

Let’s combine all the pieces

function loadJS(FILE_URL, async = true) {
  let scriptEle = document.createElement("script");

  scriptEle.setAttribute("src", FILE_URL);
  scriptEle.setAttribute("type", "text/javascript");
  scriptEle.setAttribute("async", async);

  document.body.appendChild(scriptEle);

  // success event 
  scriptEle.addEventListener("load", () => {
    console.log("File loaded")
  });
   // error event
  scriptEle.addEventListener("error", (ev) => {
    console.log("Error on loading file", ev);
  });
}
loadJS("file1_path", true);

// If we set async false, file2 is loaded and executed first, then file3 will be loaded 
loadJS("file2_path", false); 
loadJS("file3_path", true);

Using Promise to load the script file

const loadScript = (FILE_URL, async = true, type = "text/javascript") => {
    return new Promise((resolve, reject) => {
        try {
            const scriptEle = document.createElement("script");
            scriptEle.type = type;
            scriptEle.async = async;
            scriptEle.src =FILE_URL;

            scriptEle.addEventListener("load", (ev) => {
                resolve({ status: true });
            });

            scriptEle.addEventListener("error", (ev) => {
                reject({
                    status: false,
                    message: `Failed to load the script ${FILE_URL}`
                });
            });

            document.body.appendChild(scriptEle);
        } catch (error) {
            reject(error);
        }
    });
};

loadScript("file1_url")
    .then( data  => {
        console.log("Script loaded successfully", data);
    })
    .catch( err => {
        console.error(err);
    });