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.