首页  >  文章  >  web前端  >  当 `iframe.load()` 失败时,如何可靠地验证 iFrame 的加载状态?

当 `iframe.load()` 失败时,如何可靠地验证 iFrame 的加载状态?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-25 06:19:02818浏览

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

了解 iFrame 加载状态

验证 iFrame 的加载状态对于完成后执行操作或检测加载失败至关重要。本文解决了确定具有特定约束的 iFrame 加载状态的挑战。

考虑以下场景:使用提供的代码加载 ID 为“myIframe”的 iFrame。然而,加载时间各不相同,阻碍了“iframe.load()”事件的使用。

解决方案:迭代检查

为了解决这个问题,迭代检查方法可以实施。以下代码片段举例说明了此策略:

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

此代码迭代检查 iFrame 文档的“readyState”属性,确保在执行所需操作(例如,显示警报消息)之前完成加载。 iFrame 加载后,将调用“afterLoading()”函数。

以上是当 `iframe.load()` 失败时,如何可靠地验证 iFrame 的加载状态?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn