[英]how to know when an iframe has finished loading the DOM, but not yet all images?
我的網頁有一個 iframe,當用戶單擊showNewPage
按鈕時,我更改了它的 src。 我需要知道瀏覽器何時完成加載 iframe 的 DOM,但無需等待所有圖像下載完畢。
var myIFrame = document.getElementById("myIframe")
var count = 0;
funcion showNewPage() {
myIFrame.src = "http://example.com/page_" + count;
count++;
}
當 iframe 完成加載 DOM 和所有圖像時,此代碼調用doSomething()
:
myIFrame.addEventListener("load", function(event) { doSomething(); });
當 iframe 完成加載 DOM 但尚未加載所有圖像時,如何要求 myIFrame 調用doSomething()
?
ps:有一個事件DOMContentLoaded
而不是load
來實現這一點; 但此事件不適用於 iframe。 它僅適用於文檔或窗口。 執行以下操作也不起作用,因為myIFrame.contentWindow
在最開始時返回 null:
myIFrame.contentWindow.addEventListener("DOMContentLoaded", function(event) { doSomething(); });
ps:另一個問題沒有回答我的問題,因為它依賴於onload
事件,它會等到所有圖像都下載完畢: 如何檢測 iframe 何時已加載
正如您所發現的,在 iframe 初始化之前嘗試獲取其.contentWindow
將返回null
。
解決這個問題的一種方法是
about:blank
)初始化您的框架,contentWindow
的引用,這將始終是同一個對象,但是我們附加在其上的事件將在每次新導航時刪除...unload
事件偵聽器(因為它最接近導航)contentWindow
開始導航DOMContentLoaded
和我們的unload
事件偵聽器,以便我們可以在下次導航時重申frame.onload = e => {
const win = frame.contentWindow;
frame.onload = null;
win.addEventListener( 'unload', attachEvents );
YOUR_CALLBACK(); // make it fire even at beginning?
function attachEvents() {
setTimeout( () => {
win.addEventListener( 'DOMContentLoaded', YOUR_CALLBACK );
win.addEventListener( 'unload', attachEvents ); // do it again at next navigation
}, 0 );
};
};
frame.src = "about:blank";
作為一個小提琴,因為 StackSnippets 過度保護的 iframe 不允許我們訪問內部框架的內容......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.