在单独的过程中创建iframe,以免阻塞父窗口的主线程 [英] Creating an iframe in separate process so it doesn't block the main thread of the parent window

查看:87
本文介绍了在单独的过程中创建iframe,以免阻塞父窗口的主线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近听说了可以添加到锚标记中的 rel ="noopener" 属性值,以便新窗口在单独的进程中运行.那让我感到纳闷:是否有可能创建一个在单独的进程中运行的iframe,以便例如,iframe中的无限循环不会导致父窗口的主线程被阻塞?

I recently heard about the rel="noopener" attribute value that can be added to anchor tags so that the new window runs in a separate process. That got me wondering: Is it possible to create an iframe that runs in a separate process so that, for example, an infinite loop in the iframe won't cause the parent window's main thread to be blocked?

下面是一些观察主线程冻结的示例代码:

Here's some example code to observe the main-thread freeze:

<progress></progress>
<iframe srcdoc="<script>function loop() { i=0; while(i<700000000){i++}; setTimeout(loop, 2000) }; loop();</script>"></iframe>

https://jsbin.com/zabecoviwi/1/edit?html,输出

编辑:请注意,您可以通过向iframe添加 sandbox 属性来防止冻结,该属性似乎迫使"浏览器(至少是Chrome)执行以下操作:将iframe放在单独的线程中,但是我无法做到这一点.但是,我在单独的子域下提供iframe的代码,因此我一直认为,由于iframe是一个单独的来源,因此如果iframe的 src 是一个不同的顶级域.

Note that you can prevent the freezing by adding the sandbox attribute to the iframe, which seems to "force" the browser (Chrome, at least) to put the iframe in a separate thread, but I can't do this in my case. I am however serving the code for the iframe under a separate subdomain so I'd have thought that since it's a separate origin Chrome would put it in a separate process as it appears to do if the iframe's src is a different top-level domain.

推荐答案

在包括Chrome在内的某些浏览器中,跨域iframes

In some browsers, including Chrome, cross-origin iframes already run in a separate process. For example, running the following snippet in Chrome will not prevent you from scrolling in the parent Stack Overflow window:

while (true) {
}

对于尚未执行此操作的浏览器,或对于相同来源的iframe,您可以通过在iframe中的网络工作者中运行昂贵的任务来明确显示该过程:

For browsers which don't do this already, or for same origin iframes, you can make the process explicit by running the expensive tasks in a web worker in the iframe:

const workerFn = () => {
  // something expensive
  while (true) {
  }
};
const workerFnStr = `(${workerFn})();`;
const blob = new Blob([workerFnStr], { type: 'text/javascript' });
const worker = new Worker(window.URL.createObjectURL(blob));

// The worker has been created, and will continuously consume resources,
// but will not block the iframe window or the iframe's parent

body {
  height: 1000px;
}

这篇关于在单独的过程中创建iframe,以免阻塞父窗口的主线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆