gpt4 book ai didi

javascript - 如何知道 iframe 何时已完成加载 DOM,但尚未加载所有图像?

转载 作者:行者123 更新时间:2023-12-02 22:15:20 24 4
gpt4 key购买 nike

我的网页有一个 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 事件,该事件会等待所有图像下载完毕:How to detect when an iframe has already been loaded

最佳答案

正如您所发现的,在 iframe 初始化之前尝试获取其 .contentWindow 将返回 null

解决这个问题的一种方法是

  • 使用空文档 (about:blank) 初始化框架,
  • 获取对 iframe 的 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";

As a fiddle由于 StackSnippets 过度保护 iframe 不允许我们访问内部框架的内容...

关于javascript - 如何知道 iframe 何时已完成加载 DOM,但尚未加载所有图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59401017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com