Typically, we load a JavaScript file using the script
tag:
<script src="https://www.mywebsite.com/test.js"></script>
In some situations, we want to load
Those files can be loaded asynchronously in JavaScript.
To load a JavaScript file dynamically:
script
element.src
, async
, and type
attributes.script
element to the body.script
elementFirst, we need to create a script
element as given below:
let scriptEle = document.createElement("script");
src
, async
, and type
attributes.src
: the file pathtype
: 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");
script
elementWe 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.
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);
});
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);
Promise
to load the script fileconst 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);
});