简体   繁体   English

Web-Worker 导入的脚本可以反过来导入另一个脚本吗?

[英]Can a script imported by a Web-Worker in turn import another script?

The pattern for a script used by a webworker https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers is:网络工作者使用的脚本模式https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers是:

  • webworker.js

     importScripts('./parent.js')
  • parent.js

     import { PerfManager} from "./child.js";

The child.js import results in: child.js导入结果:

Uncaught SyntaxError: Cannot use import statement outside a module未捕获的语法错误:无法在模块外使用导入语句

Is there any way to implement an import within the parent.js when used by webworker.js ?有什么办法来实现内的进口parent.js被使用时webworker.js

You can start a module Worker (currently only available in Blink based browsers).您可以启动一个 模块 Worker (目前仅在基于 Blink 的浏览器中可用)。

const worker = new Worker("worker.js", { type: "module" });

Then instead of importScripts you will directly import parent.js from this worker script, which will in turn be able to import whatever dependency.然后,您将直接从这个工作脚本import parent.js ,而不是importScripts ,这将能够导入任何依赖项。

Since StackSnippets are in null-origined iframes, I have to outsource the demo to this plnkr .由于 StackSnippets 在源自 null 的 iframe 中,我必须将演示外包给这个plnkr


Note that in these browsers you could even use the dynamic import() statement from parent.js even in a non module Worker: plnkr , but this still wouldn't work in browsers that don't support module Workers .请注意,在这些浏览器中,即使在非模块 Worker 中,您甚至可以使用parent.js 中的动态import()语句: plnkr ,但这在不支持模块 Workers 的浏览器中仍然不起作用
For these you need to use only non module scripts and to use importScripts and its globals all along the chain: plnkr .对于这些,您只需要使用非模块脚本,并在整个链中使用importScripts及其全局变量: plnkr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM