强制同步 iframe 加载

Force synchronous iframe load

本文关键字:加载 iframe 同步      更新时间:2023-09-26

我有一个指向任意外部域http://A的 iframe。我想将其发送到另一个http://B用户事件的外部域。

假设http://B加载速度很慢。如果我只是设置iframe.src = "http://B",那么 iframe 将保持内容不A,直到B完全下载并可以渲染。这让用户感到困惑,因为他们要求B,但他们看到的只是A

我想从我的域加载一个页面,比如../html/loading.html,介于AB之间。假设此页面加载始终很快。

我观察到设置iframe.src是异步的。请考虑以下代码:

iframe.src = '../html/loading.html';
iframe.src = 'http://B';

这将跳过开场../html/loading.html,直接转到http://B。(无论loading.html有多快,或者B有多慢)。我也尝试这样做:

iframe.src = '../html/loading.html';
iframe.contentWindow.location.reload();
iframe.src = 'http://B';

但是,这引发了跨域错误,说我无法访问http://A contentWindow的内容(因为loading.html尚未加载,我们仍在http://A,我无法强制重新加载)。

有没有办法强制 iframe 执行 URL 的同步加载?我正在编写一个Chrome扩展程序,所以如果它必须特定于crx那也没关系。

您需要在当前 URL 加载

完成后立即加载下一个 URL,幸运的是,iframe 有一个我们可以使用的 onload 事件。

您需要执行以下操作:

iframe.src='../html/loading.html'
//load the next page after finishing loading the last one
iframe.onload=function(){iframe.src='http://B';}

试试这个:

最初 iframe 应该加载加载.html使用

    iframe.src = '../html/loading.html';

在加载.html的客户端加载事件中,应使用

    iframe.src = 'http://B';