[英]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.