Web Workers & SharedWorker
Why run JS off the main thread?
Section titled “Why run JS off the main thread?”JavaScript is single-threaded. Every script, DOM update, layout calculation, and event handler runs on one thread. When you run a long computation — parsing a large file, computing a hash, processing an image — the entire UI freezes for the duration. Scroll events stop firing, animations stutter, and clicks go unanswered.
Web Workers let you move heavy work to a background thread. The browser creates a separate JS environment with its own event loop. The main thread and the worker communicate by sending messages with postMessage and receiving them via onmessage. The two threads never share memory by default, so there are no race conditions.
flowchart LR MT["Main Thread (UI, events)"] DW["Dedicated Worker (background JS)"] MT -- "worker.postMessage(data)" --> DW DW -- "self.postMessage(result)" --> MT
Dedicated vs Shared Worker
Section titled “Dedicated vs Shared Worker”| Dedicated Worker | SharedWorker | |
|---|---|---|
| Scope | One tab / one script | All tabs of the same origin |
| Constructor | new Worker(url) | new SharedWorker(url) |
| Messaging | Direct: worker.postMessage(data) | Via MessagePort: port.postMessage(data) |
| Worker side | self.onmessage = fn | Must handle onconnect first, then listen on event.ports[0] |
| Complexity | Simple | Moderate — requires port bookkeeping |
| Use case | CPU-heavy task in one tab | Shared cache, cross-tab coordination |
What this module covers
Section titled “What this module covers”| Lesson | What you learn |
|---|---|
| index (this page) | Overview, dedicated vs shared, module map |
| web-workers | Create, message, and terminate a Dedicated Worker |
| postmessage-and-transferables | Structured clone vs zero-copy transferables |
| sharedworker | Connect multiple tabs to one SharedWorker |
| worker-patterns | Error handling, worker pools, and best practices |
Try it now
Section titled “Try it now”The snippet below creates a Dedicated Worker via a Blob URL, sends the number 10, and the worker computes Fibonacci off-thread and posts back the result.