--- url: "https://web.dev/articles/module-workers" titulek: "Threading the web with module workers | Articles | web.dev" h1: "Threading the web with module workers Stay organized with collections Save and categorize content based on your preferences." popis: "Module workers make it easy to unblock the main thread by moving expensive code to a background thread while keeping the ergonomic and performance benefits of standard JavaScript modules." jazyk: "en" kanonicka: "https://web.dev/articles/module-workers" drobecky: ["Articles", "Threading the web with module workers"] zdroj: "live" wayback_snapshot: "" stazeno: "2026-09-14 02:42:22" znaku: 10242 slov: 1405 kodovani: "iso-8859-2" sha256: "0148ac3126a4f4396608af967de17d059343f7f2852c9c0f4dd2fb2b9237cf78" --- Threading the web with module workers Stay organized with collections Save and categorize content based on your preferences. Moving heavy lifting into background threads is now easier with JavaScript modules in web workers. Jason Miller JavaScript is single-threaded, which means it can only perform one operation at a time. This is intuitive and works well for lots of cases on the web, but can become problematic when we need to do heavy lifting tasks like data processing, parsing, computation, or analysis. As more and more complex applications are delivered on the web, there's an increased need for multi-threaded processing. On the web platform, the main primitive for threading and parallelism is the [Web Workers API](https://developer.mozilla.org/docs/Web/API/Web_Workers_API/Using_web_workers). Workers are a lightweight abstraction on top of [operating system threads](https://en.wikipedia.org/wiki/Thread_%28computing%29) that expose a message passing API for inter-thread communication. This can be immensely useful when performing costly computations or operating on large datasets, allowing the main thread to run smoothly while performing the expensive operations on one or more background threads. Here's a typical example of worker usage, where a worker script listens for messages from the main thread and responds by sending back messages of its own: page.js: `const worker = new Worker('worker.js'); worker.addEventListener('message', e => { console.log(e.data); }); worker.postMessage('hello');` worker.js: `addEventListener('message', e => { if (e.data === 'hello') { postMessage('world'); } });` The Web Worker API has been available in most browsers for over ten years. While that means workers have excellent browser support and are well-optimized, it also means they long predate JavaScript modules. Since there was no module system when workers were designed, the API for loading code into a worker and composing scripts has remained similar to the synchronous script loading approaches common in 2009. History: classic workers The Worker constructor takes a [classic script](https://html.spec.whatwg.org/multipage/webappapis.html#classic-script) URL, which is relative to the document URL. It immediately returns a reference to the new worker instance, which exposes a messaging interface as well as a `terminate()` method that immediately stops and destroys the worker. `const worker = new Worker('worker.js');` An `importScripts()` function is available within web workers for loading additional code, but it pauses execution of the worker in order to fetch and evaluate each script. It also executes scripts in the global scope like a classic `` Preloaded modules can also be used by both the main thread and module workers. This is useful for modules that are imported in both contexts, or in cases where it's not possible to know in advance whether a module will be used on the main thread or in a worker. Previously, the options available for preloading web worker scripts were limited and not necessarily reliable. Classic workers had their own "worker" resource type for preloading, but no browsers implemented ``. As a result, the primary technique available for preloading web workers was to use ``, which relied entirely on the HTTP cache. When used in combination with the correct caching headers, this made it possible to avoid worker instantiation having to wait to download the worker script. However, unlike `modulepreload` this technique did not support preloading dependencies or pre-parsing. What about shared workers? [Shared workers](https://developer.mozilla.org/docs/Web/API/SharedWorker/SharedWorker) have been updated with support for JavaScript modules as of Chrome 83. Like dedicated workers, constructing a shared worker with the `{type:"module"}` option now loads the worker script as a module rather than a classic script: `const worker = new SharedWorker('/worker.js', { type: 'module' });` Prior to support of JavaScript modules, the `SharedWorker()` constructor expected only a URL and an optional `name` argument. This will continue to work for classic shared worker usage; however creating module shared workers requires using the new `options` argument. The [available options](https://html.spec.whatwg.org/multipage/workers.html#shared-workers-and-the-sharedworker-interface) are the same as those for a dedicated worker, including the `name` option that supersedes the previous `name` argument. What about service worker? The service worker specification [has already been updated](https://w3c.github.io/ServiceWorker/#service-worker-concept) to support accepting a JavaScript module as the entry point, using the same `{type:"module"}` option as module workers, however this change has yet to be implemented in browsers. Once that happens, it will be possible to instantiate a service worker using a JavaScript module using the following code: `navigator.serviceWorker.register('/sw.js', { type: 'module' });` Now that the specification has been updated, browsers are beginning to implement the new behavior. This takes time because there are some extra complications associated with bringing JavaScript modules to service worker. Service worker registration needs to [compare imported scripts with their previous cached versions](https://chromestatus.com/feature/6533131347689472) when determining whether to trigger an update, and this needs to be implemented for JavaScript modules when used for service workers. Also, service workers need to be able to [bypass the cache](https://chromestatus.com/feature/5897293530136576) for scripts in certain cases when checking for updates. Additional resources and further reading [Feature status, browser consensus and standardization](https://www.chromestatus.com/feature/5761300827209728) [Original module workers spec addition](https://github.com/whatwg/html/pull/608) [JavaScript modules for shared workers](https://www.chromestatus.com/feature/5169440012369920) JavaScript modules for service workers: [Chrome implementation status](https://bugs.chromium.org/p/chromium/issues/detail?id=824647) Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2019-12-17 UTC.