Web Worker
In short
A web worker is a browser feature that runs JavaScript on a background thread, so heavy computations don't freeze the page's user interface while they run.
What is a web worker?
JavaScript on a web page normally runs on a single main thread, which also handles rendering, clicks, and scrolling. If a script spends two seconds crunching numbers, the page freezes for those two seconds. A web worker solves this by running a separate script on a background thread, leaving the main thread free to keep the interface responsive.
You create a worker with new Worker("worker.js"), adding { type: "module" } if the worker uses import. The page and the worker communicate only by sending messages with postMessage() and listening for message events. Data is copied between threads, although large binary data such as an ArrayBuffer can be transferred instead, which is much faster. Workers have no access to the DOM or window, but they can use fetch, timers, IndexedDB, and WebAssembly. A dedicated worker belongs to one page, while a shared worker can be used by several tabs from the same site.
A web worker is like a kitchen assistant chopping vegetables in the back room while the waiter keeps serving customers; they pass notes through a hatch instead of sharing a workspace. Typical uses include image and video processing, parsing large files, encryption, syntax highlighting in code editors, and running WebAssembly modules or small machine learning models in the browser.
Web workers are often confused with service workers. A service worker is also a background script, but its job is to sit between the page and the network, intercepting requests to enable caching, offline support, and push notifications, and it can run when no page is open. A web worker exists only while its page uses it and is meant for computation. A worker also doesn't make code faster by itself: the total work is the same, it just moves off the main thread.
Key takeaways
- A web worker runs JavaScript on a background thread, separate from the main UI thread.
- The page and the worker talk only through
postMessage()andmessageevents. - Workers can't touch the DOM, but they can use
fetch, timers, and WebAssembly. - Large binary data can be transferred instead of copied to save time.
- Service workers handle network requests and offline support; web workers handle heavy computation.
Example
// main.js: hand heavy work to a background thread
const worker = new Worker("worker.js");
worker.postMessage({ limit: 10_000_000 });
worker.onmessage = (event) => console.log("Sum:", event.data);
// The page stays responsive while the worker is busy
// worker.js: no DOM access here, only messages in and out
self.onmessage = (event) => {
let sum = 0;
for (let i = 0; i < event.data.limit; i++) sum += Math.sqrt(i);
self.postMessage(sum);
};Readers ask
Can a web worker access the DOM?
No. Workers can't read or change the DOM, document, or window. They send their results back with postMessage(), and code on the main thread updates the page.
Do web workers make JavaScript multithreaded?
Each worker runs on its own thread with its own event loop, and by default workers don't share variables, so ordinary objects can't be corrupted by two threads at once. True shared memory is possible only with SharedArrayBuffer, which requires the page to be cross-origin isolated.
When should I use a web worker?
Use one when a task takes long enough to make the page stutter, roughly anything over 50 milliseconds, such as parsing a large file or processing an image. Short tasks and network requests don't need a worker, because fetch is already asynchronous.
See also
- JavaScriptWeb Development, p. 24JavaScript is the programming language that runs in web browsers to make pages interactive, and it also runs on servers through runtimes like Node.js.
- Service WorkerWeb Development, p. 40A service worker is a script the browser runs in the background, apart from the page, to intercept network requests and enable offline use and push messages.
- Event LoopBackend & APIs, p. 13The event loop is a mechanism that lets a single thread handle many tasks by running callbacks one at a time as events and I/O results become ready.
- ThreadOperating Systems, p. 33A thread is the smallest unit of execution an operating system can schedule, running inside a process and sharing that process's memory with other threads.
- WebAssemblyWeb Development, p. 59WebAssembly is a compact binary code format that runs in web browsers at near-native speed, letting languages like C++, Rust, and Go power fast web code.
- ConcurrencyProgramming Fundamentals, p. 12Concurrency is a program's ability to make progress on several tasks in overlapping time periods, such as serving many users at once rather than one at a time.
Spotted a mistake or something missing on this page?Suggest an edit