Home >Web Front-end >JS Tutorial >How to Reliably Verify an iFrame\'s Loading Status When `iframe.load()` Fails?

How to Reliably Verify an iFrame\'s Loading Status When `iframe.load()` Fails?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-25 06:19:02906browse

How to Reliably Verify an iFrame's Loading Status When `iframe.load()` Fails?

Understanding iFrame Loading Status

Verifying the loaded state of an iFrame is essential for executing actions upon completion or detecting loading failures. This article addresses the challenge of determining an iFrame's loaded status with specific constraints.

Consider the following scenario: an iFrame with id "myIframe" is loaded using the provided code. However, loading times vary, hindering the use of the "iframe.load()" event.

Solution: Iterative Checking

To overcome this issue, an iterative checking approach can be implemented. The following code snippet exemplifies this strategy:

<code class="javascript">function checkIframeLoaded() {
    // Get a handle to the iframe element
    var iframe = document.getElementById('i_frame');
    var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;

    // Check if loading is complete
    if (iframeDoc.readyState == 'complete') {
        //iframe.contentWindow.alert("Hello");
        iframe.contentWindow.onload = function() {
            alert("I am loaded");
        };
        // The loading is complete, call the function we want executed once the iframe is loaded
        afterLoading();
        return;
    }

    // If we are here, it is not loaded. Set things up so we check the status again in 100 milliseconds
    window.setTimeout(checkIframeLoaded, 100);
}

function afterLoading() {
    alert("I am here");
}

window.onload = checkIframeLoaded();</code>

This code iteratively checks the "readyState" property of the iFrame's document, ensuring the completion of loading before executing the desired actions (e.g., displaying an alert message). The "afterLoading()" function is called once the iFrame has loaded.

The above is the detailed content of How to Reliably Verify an iFrame\'s Loading Status When `iframe.load()` Fails?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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