首頁  >  文章  >  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