Categories
JavaScript Answers

How to wait for dynamically loaded script with JavaScript?

Spread the love

Sometimes, we want to wait for dynamically loaded script with JavaScript.

In this article, we’ll look at how to wait for dynamically loaded script with JavaScript.

How to wait for dynamically loaded script with JavaScript?

To wait for dynamically loaded script with JavaScript, we listen to the script element’s load event.

For instance, we write

<script
  id="hljs"
  async
  src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.0.0/highlight.min.js"
></script>

to add a script tag.

Then we write

const script = document.querySelector("#hljs");

script.addEventListener("load", () => {
  hljs.initHighlightingOnLoad();
});

to select the script tag with querySelector.

And we call addEventListener to listen its load event.

The callback is called when the script is loaded.

Conclusion

To wait for dynamically loaded script with JavaScript, we listen to the script element’s load event.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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