Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
communitycreator

How to dynamically load a JS file in JavaScript

Programming Bytes

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

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 to the body

document.body.appendChild(scriptEle);

Check the load event

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

RELATED TAGS

javascript
communitycreator
RELATED COURSES

View all Courses

Keep Exploring