How to wait for a dynamically loaded script with JavaScript?

Estimated read time 2 min read

When dynamically loading a script with JavaScript, it can be important to wait for the script to be fully loaded and executed before continuing with other code. One way to accomplish this is by using a callback function that is executed once the script has loaded.

Here’s an example of how to wait for a dynamically loaded script using JavaScript:

function loadScript(src, callback) {
  const script = document.createElement('script');
  script.src = src;
  script.onload = callback;
  document.head.appendChild(script);
}

// Call the loadScript function and wait for the script to load
loadScript('https://example.com/my-script.js', function() {
  console.log('Script loaded');
  // Perform some action after the script is loaded
});

In this example, we define a function called loadScript() that takes two arguments: the URL of the script to load and a callback function that will be executed once the script is loaded.

Inside the loadScript() function, we create a new script element and set its src attribute to the URL of the script. We then set the onload property of the script element to the provided callback function, which will be executed once the script is loaded.

We can then call the loadScript() function and pass in the URL of the script and the callback function. Once the script is loaded, the callback function will be executed, and we can perform any further actions that are required.

With this code, we can ensure that a dynamically loaded script is fully loaded and executed before continuing with other code, which can be useful in situations where we need to wait for external resources before performing certain actions.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply