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.

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.

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..!!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *