"classic" 和 "module" Web Worker 有什么区别?

What's the difference between a "classic" and "module" Web Worker?

我正在学习 JavaScript Web Worker API,使用 Mozilla Developer Network (MDN) 文档作为主要来源。 The documentation suggests 新 Worker 的构造函数接受 type 参数。根据同一文档,此 type 参数可以接受 classicmodule 的值。

遗憾的是,文档没有描述 classicmodule 之间的区别。我什么时候想使用 classicmodule 以及这两个 "types" Workers 之间有什么行为差异?

module 类型的用途与 type="module" attribute does for a script tag. It tells the browser the worker script being loaded is an ES6 module (which is necessary meta data to know how to parse and run it, as this article goes into a bit) 大致相同。

如果您的工作模块是 ES6 模块(可能带有 import 语句),您将使用它。如果启用了 CORS,它还有一个好处,即能够从不同的源加载工作人员,这是经典工作人员无法做到的(这可能是一个有吸引力的功能,即使不使用 import 语句)。

来自HTML Living Standard - Using a JavaScript module as a worker:

All of our examples so far show workers that run classic scripts. Workers can instead be instantiated using module scripts, which have the usual benefits: the ability to use the JavaScript import statement to import other modules; strict mode by default; and top-level declarations not polluting the worker's global scope.

Note that such module-based workers follow different restrictions regarding cross-origin content, compared to classic workers. Unlike classic workers, module workers can be instantiated using a cross-origin script, as long as that script is exposed using the CORS protocol. Additionally, the importScripts() method will automatically fail inside module workers; the JavaScript import statement is generally a better choice.

截至最初的 post 日期,您可能不会在生产中使用它,因为浏览器对 ES6 模块的支持不是很好。截至 2020 年,尽管大多数主流浏览器都支持脚本的 ES6 模块,但这并没有扩展到 workers。 Currently only Chrome 80+ has this feature.