Load script dynamically and add the callback in JavaScript
Today weâll show you how to dynamically load a script with callback in JavaScript. In this article, we will give you two different methods to load script text and load script by URL in JavaScript.
- How to get query string parameters from URL in JavaScript
- Validate the value by regular expression in JavaScript
- How to compare two dates in JavaScript
- How to remove duplicates from an Array in JavaScript
- JavaScript Array methods Splice vs Slice
Use the following code to dynamically load a script by URL.
function loadScriptByURL(id, url, callback) {
const isScriptExist = document.getElementById(id);
if (!isScriptExist) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = url;
script.id = id;
script.onload = function () {
if (callback) callback();
};
document.body.appendChild(script);
}
if (isScriptExist && callback) callback();
}
// load the script by passing the URL
loadScriptByURL("script-id", "<PATH_OF_SCRIPT_URL>", function () {
console.log("Script URL loaded!");
});
In the above code, we have asked to pass the three parameters as id
, url
and callback
function.
In the function, we will check if the script exists in the DOM then execute the callback
function. If itâs not exist in the DOM then load it by creating the script element and append it in body.
Dynamically load a script text
Use the following command where you can load the script text dynamically.
function loadScript(scriptText) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.innerHTML = scriptText;
document.body.appendChild(script);
}
// load script text
loadScript(`
console.log('Script text loaded!');
console.log('This is second console.');
`);
In the above function, we have to pass the script text to dynamically to load in the document using innerHTML
. Here we canât check the scriptâs existence in the dom.
Thatâs it for today.
Thank you for reading. Happy Coding..!!