首頁 > web前端 > js教程 > 主體

當 `iframe.load()` 失敗時,如何可靠地驗證 iFrame 的載入狀態?

Mary-Kate Olsen
發布: 2024-10-25 06:19:02
原創
818 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!