Categories
JavaScript Answers

How to add JavaScript callback that runs when an iframe is finished loading?

Spread the love

Sometimes, we want to add JavaScript callback that runs when an iframe is finished loading.

In this article, we’ll look at how to add JavaScript callback that runs when an iframe is finished loading.

How to add JavaScript callback that runs when an iframe is finished loading?

To add JavaScript callback that runs when an iframe is finished loading, we can listen for the readystatechange event.

To do this, we write

const iframe = document.getElementById("myIframe");

iframe.onreadystatechange = () => {
  if (iframe.readyState === "complete") {
    // ...
  }
};

to select the iframe with getElementById.

Then we set iframe.onreadystatechange to a function that runs when the readyState property changes.

If readyState for the iframe is 'complete', then the iframe‘s content is done loading.

Conclusion

To add JavaScript callback that runs when an iframe is finished loading, we can listen for the readystatechange 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 *