How to dynamically load script with 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. You can use the same method to dynamically load a script in ReactJS.
Dynamically load a script URL
Use the following code to dynamically load a script by URL.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 | 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..!!
Okay
Can we also load html in react js and when a Test button is clicked, we get the full message
You can check the conditional rendering in the React.