Web Worker API
A Web Worker runs JavaScript in a background thread. The main thread keeps painting and responding to input; the worker does the heavy lifting.
Creating one
app.js (main thread)
const worker = new Worker("worker.js", { type: "module" });
worker.postMessage({ type: "factor", number: 982451653 });
worker.addEventListener("message", (e) => {
console.log("result:", e.data);
});
worker.terminate(); // stop it for good
worker.js
self.addEventListener("message", (e) => {
if (e.data.type === "factor") {
self.postMessage(factor(e.data.number));
}
});
function factor(n) { /* … */ }
What's available inside a worker
| Yes | No |
|---|---|
fetch, setTimeout, setInterval | The DOM (document, window) |
IndexedDB, caches | localStorage |
WebSocket, WebRTC | Direct DOM access |
ES modules with import | Synchronous network calls |
OffscreenCanvas | — |
Three worker flavours
| Type | Use |
|---|---|
| Dedicated Worker | One worker, one page — the example above. |
| Shared Worker | One worker shared across tabs of the same origin. |
| Service Worker | Proxy for network requests; powers PWAs and offline. |
Transferable objects — zero-copy hand-off
JS
// Buffer ownership moves to the worker — main thread cannot use it anymore
const buf = new ArrayBuffer(1024 * 1024);
worker.postMessage({ buf }, [buf]);
Tip: Reach for a worker when you spot main-thread frame drops during heavy work — image processing, parsing big JSON, search indexes. Below ~5 ms of CPU per call, the message overhead isn't worth it.
Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from Web Worker API!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Send a job to a worker.
worker.
({ type: 'render', data });
Two words concatenated.
Discussion
Loading…