javascriptweb-worker

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


I'm learning about the JavaScript Web Worker APIs, using the Mozilla Developer Network (MDN) documentation as a primary source. The documentation suggests that the constructor for a new Worker accepts a type parameter. This type parameter can accept values of either classic or module, according to the same document.

Unfortunately, the documentation doesn't describe the difference between classic and module. When would I want to use classic vs. module and what behavioral differences are there between the two "types" of Workers?


Solution

  • The module type serves roughly the same purpose as the 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).

    You would use it if your worker module was an ES6 module (possibly with import statements). It also has the bonus of being able to load a worker from a different origin if CORS are enabled, which classic workers cannot (which might be an attractive feature, even if not using import statements).

    From 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.

    As of the original post date, you probably wouldn't have used it in production as browser support was not available. Support for ES6 modules in workers lagged behind support for regular scripts.