In web development, it's often necessary to dynamically load content into an iFrame. To ensure proper functionality and avoid potential errors, it's crucial to determine when the iFrame has successfully loaded and contains content.
Problem:
Consider an iFrame with a variable loading time. You need a way to detect whether the iFrame has finished loading or acquired content. Approaches such as iframe.contents().find() or iframe.load(function()) may not always be feasible.
Solution:
Here's a JavaScript function that effectively checks for an iFrame's loaded state:
<code class="javascript">function checkIframeLoaded() { // Get iframe reference var iframe = document.getElementById('i_frame'); var iframeDoc = iframe.contentDocument || iframe.contentWindow.document; // Check if loading is complete if (iframeDoc.readyState == 'complete') { // Loading is complete afterLoading(); return; } // Set timeout for re-checking window.setTimeout(checkIframeLoaded, 100); } function afterLoading(){ // Execute desired code after iFrame load }</code>
In the
of your HTML document, add the following:<code class="html"><body onload="checkIframeLoaded();"></code>
This function periodically checks the iFrame's readyState property, which indicates its load status. When readyState equals 'complete,' the iFrame has loaded, and you can execute any desired code through the afterLoading() function.
The above is the detailed content of **How to Reliably Determine if an iFrame Has Loaded and Contains Content?**. For more information, please follow other related articles on the PHP Chinese website!