Home > Article > Web Front-end > How to Reliably Check if an IFrame is Loaded and Ready for Interaction in JavaScript?
How to Check if an IFrame is Loaded or Has Content
When dealing with iframes that can take varying amounts of time to load, it becomes necessary to determine their loading status. This article presents a reliable solution to check if an iframe is loaded or has content.
The provided code utilizes JavaScript's setTimeout function to periodically check the iframe's status. The key here lies in the checkIframeLoaded function, which employs a recursive approach to continuously check the iframe's readyState property.
If the loading process is complete, as indicated by a readyState value of "complete," the afterLoading function is called. This function performs the desired actions after the iframe is loaded.
Here's the code snippet:
<code class="javascript">function checkIframeLoaded() { // Get iframe element var iframe = document.getElementById('i_frame'); var iframeDoc = iframe.contentDocument || iframe.contentWindow.document; // Check loading status if (iframeDoc.readyState == 'complete') { // Loading complete, call afterLoading function afterLoading(); return; } // Not loaded, check again in 100 milliseconds window.setTimeout(checkIframeLoaded, 100); } function afterLoading(){ alert("Iframe loaded"); }</code>
To use this solution, simply include the code in your HTML body tag or call checkIframeLoaded manually when the iframe is ready to be loaded. This approach effectively handles varying iframe loading times and allows you to perform actions once the iframe is fully loaded or has content.
The above is the detailed content of How to Reliably Check if an IFrame is Loaded and Ready for Interaction in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!