Home > Web Front-end > JS Tutorial > How to Reliably Check if an IFrame is Loaded and Ready for Interaction in JavaScript?

How to Reliably Check if an IFrame is Loaded and Ready for Interaction in JavaScript?

Mary-Kate Olsen
Release: 2024-10-25 02:50:02
Original
897 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template