Web Workers are a browser feature for running JavaScript on a separate background thread. A script normally runs on the main thread, which also handles rendering and input; a worker has its own thread and event loop, so long tasks do not block the interface.
Why it matters
A computation that takes 300 ms on the main thread makes the page feel frozen and hurts responsiveness metrics. Moving parsing, compression, image processing, search indexing or large sorts into a worker keeps scrolling and clicks smooth. Workers cannot access the DOM. They communicate with the page by passing messages, which are copied (or transferred, for large buffers) rather than shared directly.
Example
// main.js
const worker = new Worker("sum.js");
worker.postMessage([1, 2, 3, 4]);
worker.onmessage = (e) => console.log(e.data); // 10
// sum.js
onmessage = (e) => {
postMessage(e.data.reduce((a, b) => a + b, 0));
};
Service workers and shared workers are related but serve different purposes.
Common mistakes
- Using a worker for tiny tasks, where messaging overhead exceeds the gain.
- Trying to read the DOM or
windowinside a worker. - Copying huge objects back and forth instead of transferring buffers.
- Forgetting to call
terminate()when finished.
Related
Get notified when this term updates
Plus occasional practical tips on uptime and monitoring, nothing else. Unsubscribe anytime.
This page is general information written by our editorial team and updated when documentation changes. Servers and providers differ, so test changes safely first. See our editorial policy and disclaimer.