javascript - 新建iframe并同步加载内容

标签 javascript jquery html firefox iframe

目标是动态创建一个 iframe,并同步将 SVG 元素附加到其文档主体。

我们正在努力让它在 Firefox 中运行。

我们的研究表明,在将 iframe 附加到 HTML 后,Firefox 会使用新文档重置 iframe。这会触发一个加载事件,只有在这个事件之后你才能成功追加内容。在加载事件之前附加的任何内容都会被丢弃。

不理想的解决方法是等待加载事件,然后将 SVG 元素附加到 iframe。

是否可以避免异步行为?我们希望在创建 iframe 后同步附加 SVG 元素。

代码笔:https://codepen.io/anon/pen/yWXjgM

var newElem = $(document.createElement("div"));
newElem.html("hi there");
var iframe = $(document.createElement("iframe"));
iframe.contents().find("body").append(newElem);
$("#box").append(iframe);
$("#box").append(newElem);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="box"></div>

最佳答案

tl:dr 无论采取什么措施,正在加载的 iframe 的异步特性似乎都无法避免,但是可以通过同步方式添加内容通过 srcdoc 动态到 iframe它“覆盖”了默认的 iframe src属性不被使用。

它也会出现可能是使用createHTMLDocument 的解决方案但我还没有成功。

解决方案 srcdoc

解释

假设您的动态 iframe 不通过 src 加载内容属性

根据HTML iframe specifications

When an iframe element is inserted into a document that has a browsing context, the user agent must create a nested browsing context, and then process the iframe attributes for the "first time".

需要注意的是“第一次处理iframe属性”。 没有提及这个过程是同步的还是异步的,它取决于每个浏览器的实现。

如前所述,Chrome 和 Firefox 已将此过程理解为异步过程,这确实有意义,因为 iframe 的目标是从其 src 加载内容。属性并调用 onload回调。

如果没有src属性可用,它将设置为 "about:blank"

值得一提的是在浏览器检查之前是否有src属性存在,它会首先检查是否 srcdoc根据 MDN iframe doc 可用:

srcdoc

Inline HTML to embed, overriding the src attribute. If a browser does not support the srcdoc attribute, it will fall back to the URL in the src attribute.

工作示例

const container = document.getElementById("container");
const iframe = document.createElement("iframe");

iframe.addEventListener("load", function(){
  console.log("loaded...");
});

iframe.srcdoc = `
  <svg height="100" width="100">
      <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
      Sorry, your browser does not support inline SVG.  
  </svg>
`;

iframe.srcdoc += `
  <svg height="100" width="100">
      <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="blue" />
      Sorry, your browser does not support inline SVG.  
  </svg>
`

container.append(iframe);
<div id="container"></div>

Web 扩展解决方案

如果您正在开发网络扩展,您将可以访问 mozbrowser api因此 stop

The stop() method of the HTMLIFrameElement interface is used to stop loading the content of the <iframe>.

关于javascript - 新建iframe并同步加载内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56195634/

相关文章:

javascript - 控制台中 Jquery 的 Google Chrome 开发者工具问题

asp.net - 在新窗口中写入输出流

javascript - 如何从特定事件目标获取数据

html - 使用 itextsharp 绘制完整的线条

javascript - jQuery slideDown 和 slideUp 不是动画

javascript - iOS 上 Sygic 的自定义架构的奇怪行为

javascript - 在 JavaScript 中将一个月添加到日期

jQuery 插入元素没有父级调整大小

未检测到 Javascript 字符串比较

jquery - 如何在 Chrome 扩展程序弹出窗口显示后触发事件?