Dedicated, Shared, Service Workers & Offscreen Rendering
JavaScript is single-threaded, but the browser does not have to be. Web Workers let you run code on separate threads — keeping the main thread free for rendering and interactions. This guide covers every worker type, how to manage them at scale, and when to reach for them in your architecture.
FrontendX EngineeringSystem Design Series
What Are Web Workers?
Web Workers are the browser's answer to parallelism. They let you run JavaScript in a separate operating-system thread, completely isolated from the main thread. The worker has its own event loop, its own global scope, and no access to the DOM, window, or document. Communication happens exclusively through message passing — postMessage on one side, onmessage on the other.
Why does this matter? The main thread is responsible for rendering, event handling, and running your JavaScript. If your code blocks for more than 50 ms, the user sees jank — frames drop, scrolling stutters, taps feel unresponsive. Web Workers pull expensive work off the main thread, keeping the UI buttery smooth while computation happens in the background.
There are three types of workers, each with a distinct role: Dedicated Workers are one-to-one with their creator. Shared Workers can be accessed from multiple tabs. Service Workers act as network proxies for offline support, caching, and push notifications. We will cover all three — plus patterns like worker pooling, transferables, OffscreenCanvas, and Comlink that make them practical at scale.
Figure 1 — The three Web Worker types. Each serves a different purpose in a frontend architecture.
Key Insight
Web Workers are not "lightweight threads." Each worker spins up its own JavaScript VM instance, which means ~5 MB of memory overhead per worker. Spawn them deliberately, pool them, and terminate them when idle.
1 · The Three Worker Types
Before diving into each type, here is the quick decision framework:
The browser support story is strong: all three types are supported in every modern browser. Shared Workers have a slight caveat — they require the page to be served over HTTPS or localhost. Service Workers require HTTPS everywhere (even localhost counts). Dedicated Workers work on HTTP, HTTPS, and even file:// in most browsers.
Warning
Service Workers require HTTPS. They will not register on insecure origins (except localhost during development). This is a security feature — Service Workers can intercept and modify network requests, so they must be served over a trustworthy connection.
2 · Dedicated Workers — The Workhorse
Dedicated Workers are the simplest and most widely used worker type. You create one with new Worker("script.js"), send it messages with worker.postMessage(), and receive results via the message event. The worker is tied to the document that created it — navigate away, and the worker dies.
Inside the worker, you have access to a subset of browser APIs: fetch, setTimeout, requestAnimationFrame (in some implementations), IndexedDB, WebAssembly, and the Cache API. What you do not have:document, window, parent, or any DOM methods.
worker.jstypescript
// ===== worker.js — the worker script =====// Runs in a separate thread with its own global scope// Listen for messages from the main threadself.addEventListener("message", (event: MessageEvent) => { const { type, payload } = event.data; switch (type) { case "COMPUTE_PRIMES": { const { limit } = payload; const primes = sieveOfEratosthenes(limit); self.postMessage({ type: "PRIMES_RESULT", payload: primes }); break; } case "PROCESS_IMAGE": { const { imageData } = payload; const result = applyFilter(imageData); // Transfer the buffer back — zero-copy self.postMessage( { type: "IMAGE_RESULT", payload: result }, [result.data.buffer], ); break; } default: self.postMessage({ type: "ERROR", payload: "Unknown request" }); }});// Heavy computation: sieve of Eratosthenesfunction sieveOfEratosthenes(limit: number): number[] { const sieve = new Uint8Array(limit + 1); const primes: number[] = []; for (let i = 2; i <= limit; i++) { if (!sieve[i]) { primes.push(i); for (let j = i * i; j <= limit; j += i) { sieve[j] = 1; } } } return primes;}// Simple image filter (grayscale)function applyFilter(data: ImageData): ImageData { for (let i = 0; i < data.data.length; i += 4) { const avg = (data.data[i] + data.data[i + 1] + data.data[i + 2]) / 3; data.data[i] = avg; // R data.data[i + 1] = avg; // G data.data[i + 2] = avg; // B // Alpha unchanged } return data;}
Inline workers with Blob URLs
Sometimes you want the worker code in the same file as your main thread code — especially during prototyping or when you need to dynamically generate worker logic. You can create a worker from a Blob URL:
inline-worker.tstypescript
// Inline worker using a Blob URL
const workerCode = `
self.addEventListener("message", (event) => {
const result = event.data * 2;
self.postMessage(result);
});
`;
const blob = new Blob([workerCode], { type: "application/javascript" });
const url = URL.createObjectURL(blob);
const worker = new Worker(url);
worker.postMessage(21);
worker.onmessage = (event) => {
console.log(event.data); // 42
URL.revokeObjectURL(url); // Clean up
};
This pattern is useful for bundler-free setups or when usingnew Function() style worker generation. The tradeoff is that the worker code exists as a string, so you lose syntax highlighting and type checking in the worker portion.
Module workers
Modern browsers support ES Module workers — workers that use import and export like regular modules. Pass { type: "module" } as the second argument to the Worker constructor:new Worker("worker.js", { type: "module" }). This enables clean code organization in workers, shared utility imports, and static analysis benefits. Module workers are supported in Chrome 80+, Firefox 114+, and Safari 15+.
Tip
Use module workers whenever possible. They support import/export, get proper TypeScript tooling with bundlers, and compose better with your existing build pipeline. The syntax is cleaner thanimportScripts(), which loads scripts synchronously and blocks the worker.
3 · Shared Workers — Cross-Tab Coordination
Shared Workers are the middle child of the worker family. A single Shared Worker instance can be accessed from multiple browsing contexts — tabs, iframes, and even other workers — as long as they share the same origin. Communication happens through MessagePort objects, which the worker receives via the connect event.
Shared Workers are ideal for scenarios where multiple tabs need to share state or coordinate actions: a music player that should pause when another tab starts playing, a real-time collaboration tool that needs to broadcast changes, or a shared cache that avoids redundant network requests across tabs.
shared-worker.jstypescript
// ===== shared-worker.js =====// Shared across all tabs/windows on the same originconst connections = new Set<MessagePort>();self.addEventListener("connect", (event: MessageEvent) => { const port = event.ports[0]; connections.add(port); port.postMessage({ type: "CONNECTED", payload: { peers: connections.size } }); port.addEventListener("message", (msgEvent: MessageEvent) => { const { type, payload } = msgEvent.data; switch (type) { case "BROADCAST": { // Relay message to all other tabs for (const conn of connections) { if (conn !== port) { conn.postMessage({ type: "TAB_MESSAGE", payload }); } } break; } case "GET_STATE": { port.postMessage({ type: "STATE", payload: { sharedCount: sharedCounter }, }); break; } case "INCREMENT": { sharedCounter += payload.by ?? 1; for (const conn of connections) { conn.postMessage({ type: "COUNT_UPDATED", payload: { count: sharedCounter }, }); } break; } } }); port.start(); port.addEventListener("close", () => { connections.delete(port); });});let sharedCounter = 0;// ===== main-thread.js — connecting from any tab =====const worker = new SharedWorker("./shared-worker.js");worker.port.start();worker.port.addEventListener("message", (event) => { console.log("Received from shared worker:", event.data);});// Broadcast to all tabsworker.port.postMessage({ type: "BROADCAST", payload: { text: "User liked a post!" },});
Shared Worker lifecycle
A Shared Worker lives as long as there is at least one connected port. When the last tab closes or calls port.close(), the worker is terminated. This means Shared Worker state is inherently ephemeral — do not rely on it for persistent data. Use IndexedDB or the Cache API for durable storage, and use the Shared Worker for coordination and ephemeral state.
Note
Shared Workers have a quirk: if the worker script filename changes (e.g., due to a bundler hash), every tab gets a new worker instance. The old worker will eventually terminate when all its ports disconnect. Be mindful of this during deployments with cache-busting filenames.
Alternatives to Shared Workers
BroadcastChannel API: A simpler pub/sub channel for cross-tab communication. Does not require a worker at all.
localStorage events: The storage event fires when another tab changes localStorage. Limited but surprisingly useful.
IndexedDB: Can be used as a crude shared state mechanism by polling or using the databases API.
Key Insight
Shared Workers are the least-used worker type — not because they are not useful, but because the use cases are specific. Reach for them when you need real-time coordination across tabs (multi-player games, collaborative editing, shared media controls). For simpler cross-tab messaging, BroadcastChannel is often enough.
4 · Service Workers — Network Proxy & Offline
Service Workers are the most powerful — and most complex — worker type. They act as a programmable network proxy that sits between your web app and the network. Every HTTP request your page makes passes through the Service Worker's fetch event handler, where you can serve cached responses, forward to the network, or return a custom fallback.
Service Workers enable the holy grail of web experiences: offline-first. Combined with the Cache API, you can pre-cache your app shell during installation, serve from cache when the network is unavailable, and update the cache in the background when connectivity returns. They also power push notifications, background sync, and periodic background updates.
Unlike other workers, Service Workers have a well-defined lifecycle managed by the browser:
Registration:navigator.serviceWorker.register(url)triggers the install.
Install: Fires once per version. This is where you pre-cache your app shell. If the install fails (e.g., a cache addAll rejects), the worker is discarded.
Waiting: After a successful install, the worker waits until all existing tabs using the old version are closed. You can skip this with self.skipWaiting().
Activate: The old cache is cleaned up here. You can take control of uncontrolled clients with clients.claim().
Fetch / Push / Sync: The worker is now running and handling events. It stays active until the browser decides to terminate it (or a new version replaces it).
Caching strategies
Strategy
Behavior
Best for
Cache first
Return cached, fall back to network
Static assets (JS, CSS, fonts, images)
Network first
Try network, fall back to cache
API responses, dynamic content
Stale-while-revalidate
Return cached, fetch in background, update cache
HTML pages, blog posts, user profiles
Network only
Always go to the network, never cache
Real-time data, analytics, sensitive operations
Warning
Service Worker caching is not free. A large CacheStorage consumes disk space and can slow down cold starts. Set cache size limits and purge old entries during activation. On low-memory devices, consider skipping the Service Worker entirely to conserve resources.
5 · Worker Pooling — Managing Parallelism
Creating a new Worker for every task is wasteful. Each worker spawns its own JavaScript VM, incurring memory overhead (~5 MB baseline) and a startup cost (50-200 ms depending on the script size). Worker pooling solves this by maintaining a fixed set of pre-created workers, dispatching tasks to idle ones, and queuing tasks when all workers are busy.
A well-designed pool matches its size to the device's hardware concurrency — typically navigator.hardwareConcurrency - 1, leaving one logical core for the main thread. On a quad-core device, that gives you three workers. On an octa-core, seven. This prevents oversubscription, where too many workers compete for CPU time and degrade performance.
Figure 3 — Worker pool architecture. A fixed pool avoids the overhead of spawning workers per-task.
worker-pool.tstypescript
// ===== WorkerPool — manage a fixed set of workers =====type Task<T = unknown> = { id: string; data: unknown; resolve: (value: T) => void; reject: (reason: unknown) => void;};export class WorkerPool { private workers: Worker[] = []; private idleWorkers: Worker[] = []; private taskQueue: Task[] = []; private activeTasks = new Map<string, Worker>(); private workerId = 0; constructor( private workerScript: string, private poolSize: number, ) { this.initPool(); } private initPool() { for (let i = 0; i < this.poolSize; i++) { const worker = new Worker(this.workerScript); worker.addEventListener("message", (event) => this.onTaskComplete(worker, event), ); worker.addEventListener("error", (event) => this.onTaskError(worker, event), ); this.workers.push(worker); this.idleWorkers.push(worker); } } exec<T>(data: unknown): Promise<T> { return new Promise<T>((resolve, reject) => { const task: Task<T> = { id: crypto.randomUUID(), data, resolve, reject, }; const idleWorker = this.idleWorkers.pop(); if (idleWorker) { this.assignTask(idleWorker, task); } else { this.taskQueue.push(task); } }); } private assignTask(worker: Worker, task: Task) { this.activeTasks.set(task.id, worker); worker.postMessage(task.data); } private onTaskComplete(worker: Worker, event: MessageEvent) { const taskId = this.findTaskIdForWorker(worker); if (!taskId) return; const task = this.findTask(taskId); this.activeTasks.delete(taskId); task?.resolve(event.data); // Reassign from queue or return to pool const next = this.taskQueue.shift(); if (next) { this.assignTask(worker, next); } else { this.idleWorkers.push(worker); } } private onTaskError(worker: Worker, event: ErrorEvent) { const taskId = this.findTaskIdForWorker(worker); if (!taskId) return; const task = this.findTask(taskId); this.activeTasks.delete(taskId); task?.reject(event.error ?? new Error("Worker error")); // Re-create the worker and retry or queue const idx = this.workers.indexOf(worker); if (idx !== -1) { this.workers[idx] = new Worker(this.workerScript); this.idleWorkers.push(this.workers[idx]); } } private findTaskIdForWorker(worker: Worker): string | undefined { for (const [id, w] of this.activeTasks) { if (w === worker) return id; } return undefined; } private findTask(id: string): Task | undefined { return this.taskQueue.find((t) => t.id === id); } get pendingTasks(): number { return this.taskQueue.length; } get activeWorkerCount(): number { return this.activeTasks.size; } destroy() { for (const worker of this.workers) { worker.terminate(); } this.workers = []; this.idleWorkers = []; this.taskQueue = []; this.activeTasks.clear(); }}// ===== Usage =====const pool = new WorkerPool("./compute-worker.js", navigator.hardwareConcurrency - 1);// Fire off parallel tasksconst results = await Promise.all([ pool.exec<number[]>({ type: "COMPUTE_PRIMES", limit: 100_000 }), pool.exec<number[]>({ type: "COMPUTE_PRIMES", limit: 500_000 }), pool.exec<number[]>({ type: "COMPUTE_PRIMES", limit: 1_000_000 }),]);console.log("All computations complete:", results);pool.destroy();
Pool sizing guidelines
Single-core / 2 GB RAM: No pool. Use a single dedicated worker for critical tasks only.
Dual-core / 4 GB RAM: Pool of 1-2 workers. Limit to non-blocking tasks.
Quad-core / 8 GB RAM: Pool of 3 workers. Suitable for most applications.
8+ cores / 16+ GB RAM: Pool of up to 7 workers. Enable heavy parallel processing.
Tip
Measure before and after. The benefit of worker pooling depends on your workload. For short-lived tasks (under 100 ms), the overhead of messaging may outweigh the parallelism gain. Profile with and without workers to validate your assumptions.
6 · Transferables — Zero-Copy Data Passing
When you call worker.postMessage(data), the browser serializes data using the structured clone algorithm. This algorithm can handle complex objects — including nested arrays, maps, sets, blobs, and even ImageData — but it creates a deep copy. For small messages this is fine. For large payloads — a 100 MB image buffer, a parsed CSV with millions of rows — the copy can take hundreds of milliseconds and double memory usage.
Transferable objects solve this by transferring ownership instead of copying. When you pass a transferable in the transfer list — the third argument to postMessage — the source object becomes detached (empty) on the sending side and is available on the receiving side. The operation is zero-copy and O(1) — constant time regardless of the buffer size.
transferables.tstypescript
// ===== Transferable objects — zero-copy data passing =====//// Without transferables: the browser serializes data via structured clone.// For a 100 MB ArrayBuffer, that means copying 100 MB to the worker.//// With transferables: ownership transfers to the worker.// The source buffer becomes empty (detached). Zero-copy.// ===== Main thread =====const worker = new Worker("./processor.js");// Create a large bufferconst buffer = new ArrayBuffer(100 * 1024 * 1024); // 100 MBconst view = new Uint8Array(buffer);// Fill with datafor (let i = 0; i < view.length; i++) { view[i] = i % 256;}// Send with transfer — buffer becomes empty on the main threadworker.postMessage({ type: "PROCESS", data: buffer }, [buffer]);console.log(buffer.byteLength); // 0 — detached!// ===== worker.js =====self.addEventListener("message", (event: MessageEvent) => { const { type, data } = event.data; if (type === "PROCESS") { // data is an ArrayBuffer — we own it now const view = new Uint8Array(data); // Process the data in-place for (let i = 0; i < view.length; i++) { view[i] = view[i] * 2; } // Transfer it back self.postMessage({ type: "RESULT", data }, [data]); }});// ===== What can be transferred? =====// ArrayBuffer — raw binary data// MessagePort — for communication channels// ImageBitmap — canvas bitmap data// OffscreenCanvas — offscreen rendering context// ReadableStream — streaming data// WritableStream — streaming data// TransformStream — streaming data// WebSocket — in some browsers// VideoFrame — video processing
When to use transferables
Image processing: Transfer ImageData.data.buffer (an ArrayBuffer) to a worker for filters, resize, or compression. Transfer back when done.
WebAssembly: Transfer WebAssembly.Memory to share memory between threads without serialization overhead.
Large datasets: For parsed CSV, JSON, or protobuf data, pack into an ArrayBuffer and transfer.
Canvas rendering: Transfer OffscreenCanvas or ImageBitmap to a worker for off-thread rendering.
Key Insight
Transferables are invisible to structured clone for most types — ArrayBuffer, MessagePort, ImageBitmap, OffscreenCanvas, ReadableStream, WritableStream, TransformStream. Always pass them in the transfer list for large data. The pattern isworker.postMessage(data, [data.buffer]).
7 · OffscreenCanvas — Rendering in Workers
Canvas rendering is expensive. Animations, data visualizations, image filters, and particle effects can easily eat 10+ ms per frame — eating into the browser's 16 ms frame budget (at 60fps) and leaving little time for layout, painting, and JavaScript execution on the main thread.
OffscreenCanvas lets you transfer a canvas rendering context to a Web Worker. The worker takes full ownership of the canvas — it draws, animates, and renders entirely off the main thread. The main thread sees zero paint overhead from that canvas, leaving it free to handle input, layout, and other critical work.
offscreen-canvas.tstypescript
// ===== OffscreenCanvas — render from a worker =====//// Main thread transfers a canvas to the worker.// The worker does all rendering, freeing the main thread.// ===== Main thread =====const canvas = document.getElementById("myCanvas") as HTMLCanvasElement;// Transfer control to the workerconst offscreen = canvas.transferControlToOffscreen();const renderWorker = new Worker("./renderer.js");renderWorker.postMessage({ canvas: offscreen }, [offscreen]);// Main thread is now free — no paint overhead// The worker owns the canvas context entirely// ===== renderer.js =====let ctx: OffscreenCanvasRenderingContext2D | null = null;self.addEventListener("message", (event: MessageEvent) => { const { canvas, type, payload } = event.data; if (canvas) { // We received the OffscreenCanvas ctx = canvas.getContext("2d"); if (ctx) { startRenderLoop(); } return; } if (type === "RESIZE") { canvas.width = payload.width; canvas.height = payload.height; }});function startRenderLoop() { let hue = 0; function frame() { if (!ctx) return; const { width, height } = ctx.canvas; // Clear ctx.fillStyle = "#0a0a0f"; ctx.fillRect(0, 0, width, height); // Draw animated elements hue = (hue + 0.5) % 360; for (let i = 0; i < 50; i++) { const x = Math.sin(Date.now() * 0.001 + i * 0.5) * width * 0.3 + width * 0.5; const y = Math.cos(Date.now() * 0.0013 + i * 0.7) * height * 0.3 + height * 0.5; const radius = 20 + Math.sin(Date.now() * 0.002 + i) * 10; ctx.beginPath(); ctx.arc(x, y, radius, 0, Math.PI * 2); ctx.fillStyle = `hsl(${(hue + i * 7) % 360}, 80%, 60%)`; ctx.fill(); } // Request next frame from the worker's perspective requestAnimationFrame(frame); } requestAnimationFrame(frame);}// ===== Benefits =====// 1. Main thread is never blocked by canvas rendering// 2. Animations continue even if the main thread is busy// 3. Heavy paint operations don't affect UI responsiveness// 4. Multiple OffscreenCanvases in multiple workers
What OffscreenCanvas unlocks
Jank-free animations: Particle systems, physics simulations, and procedural animations run entirely in a worker. The main thread never drops a frame.
Data visualizations: Render charts, graphs, and maps in a worker. The visualization stays smooth even when the main thread is busy with data loading, parsing, and layout.
Image processing: Apply filters, color grading, and transformations without blocking the UI. Chain multiple workers for parallel image processing.
Multiple canvases: Spin up multiple OffscreenCanvases across multiple workers, each rendering independently. Great for dashboards, video walls, or multi-viewport applications.
Warning
OffscreenCanvas does not support all canvas operations in a worker. Some text measurement APIs and certain blend modes are unavailable. Test your specific rendering code against the OffscreenCanvas spec. The 2D context is well-supported; WebGL context support varies by browser.
requestAnimationFrame in workers
In dedicated workers, requestAnimationFrame is available in Chromium browsers. This means your worker can run its own render loop synced to the display refresh rate, without any main thread involvement. In other browsers, use setTimeout with a target interval of 16 ms as a fallback. The animation quality will be slightly less consistent, but the worker offload benefit remains.
8 · Comlink — RPC-Style Worker Communication
Raw postMessage works, but it is boilerplate-heavy. Every message needs a type discriminator, payload extraction, error handling, and result routing. For complex worker APIs — an image processor with 15 methods, a data store with CRUD operations — the message dispatching code becomes a maintenance burden.
Comlink (by the Chrome team) eliminates this boilerplate. It wraps a worker as a proxy object — you call methods on the proxy like async functions, and Comlink handles the serialization, transfer, and result routing under the hood. It is the difference between writing an RPC framework and just calling a function.
comlink-pattern.tstypescript
// ===== Comlink — RPC-style worker communication =====//// Instead of manual postMessage/onmessage boilerplate,// Comlink wraps workers as async proxy objects.//// npm install comlink// ===== worker.js =====import { expose } from "comlink";// Define an API classclass ImageProcessor { async grayscale(imageData: ImageData): Promise<ImageData> { for (let i = 0; i < imageData.data.length; i += 4) { const avg = (imageData.data[i] + imageData.data[i + 1] + imageData.data[i + 2]) / 3; imageData.data[i] = avg; imageData.data[i + 1] = avg; imageData.data[i + 2] = avg; } return imageData; } async resize( imageData: ImageData, scale: number, ): Promise<ImageData> { // ... resize logic (omitted for brevity) return imageData; } async computePrimes(limit: number): Promise<number[]> { const sieve = new Uint8Array(limit + 1); const primes: number[] = []; for (let i = 2; i <= limit; i++) { if (!sieve[i]) { primes.push(i); for (let j = i * i; j <= limit; j += i) { sieve[j] = 1; } } } return primes; }}expose(ImageProcessor);// ===== Main thread =====import { wrap } from "comlink";// Wrap the worker — returns an async proxyconst processor = wrap<ImageProcessor>( new Worker(new URL("./worker.js", import.meta.url)),);// Call worker methods like async functions — no postMessage boilerplate!const primes = await processor.computePrimes(10_000_000);console.log(`Found ${primes.length} primes`);// Transferables are handled automatically by Comlinkconst canvas = document.getElementById("canvas") as HTMLCanvasElement;const ctx = canvas.getContext("2d")!;const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);const processed = await processor.grayscale(imageData);ctx.putImageData(processed, 0, 0);// Terminate when doneprocessor[Symbol.dispose]();
How Comlink works
expose() in the worker registers an object as remotely callable. wrap() on the main thread returns a proxy that translates method calls into postMessage calls and awaits the response. The proxy handles:
Serialization — automatic structured clone for function args and return values.
Transferables — Comlink automatically transfers ArrayBuffer and other transferable return values.
Error propagation — errors thrown in the worker are re-thrown on the main thread as proper Error objects.
TypeScript support — you get full type safety on the proxy if you type the wrap generic.
Comlink with transferables
Comlink automatically detects transferables in return values and function arguments. If your worker method returns an ArrayBuffer or ImageBitmap, Comlink adds it to the transfer list automatically. You get zero-copy performance without manually managing transfer lists.
Tip
Comlink is a great fit for complex worker APIs but adds ~3 kB (minified) to your bundle. For simple one-method workers where you only need a single "compute this" call, raw postMessage is leaner. Use Comlink when the worker has 3+ callable methods or when you need TypeScript type safety across the worker boundary.
9 · When to Use Web Workers
Web Workers are powerful, but they are not free. Each worker comes with memory overhead, serialization cost, and architectural complexity. The decision to use one should be driven by data — measure the work that is blocking your main thread, then decide whether offloading is worth the cost.
Figure 4 — Decision flow: when to use which Web Worker type.
Good candidates for Web Workers
Data parsing and serialization: Parsing large CSV/JSON/XML files, protobuf decoding, binary format parsing.
Image and video processing: Resizing, filtering, color correction, format conversion, compression.
Scientific computation: Prime sieves, matrix operations, physics simulations, cryptography.
Code transformation: Babel/TypeScript compilation, minification, linting in the browser.
Canvas/WebGL rendering: OffscreenCanvas for data viz, animations, 3D rendering, particle systems.
Poor candidates for Web Workers
DOM manipulation: Workers cannot access the DOM. If your task modifies the DOM, it must stay on the main thread. Use requestAnimationFrame or scheduler.yield() to break up long DOM tasks.
Simple state updates: Toggling a boolean, incrementing a counter, concatenating a string — these take microseconds. The messaging overhead would dominate.
Tiny payloads, frequent calls: If your task runs in under 1 ms but runs 1000 times, the serialization + messaging cost per call will be higher than just running it on the main thread. Batch instead.
Figure 2 — Worker communication patterns. Messages are serialized via the structured clone algorithm unless transferables are used.
Key Insight
The 50 ms rule: if a synchronous task takes less than 50 ms, it is usually not worth the worker overhead. Use requestAnimationFrame to split it across frames instead. If it takes more than 50 ms and is not DOM-dependent, a worker is the right tool.
10 · Key Takeaways
Web Workers are one of the most effective tools for keeping your app responsive. Here is what to remember:
Choose the right worker type. Dedicated for compute, Shared for cross-tab coordination, Service Worker for offline and caching. Each has a distinct purpose.
Pool your workers. Spinning up a worker per task wastes memory and time. Use a fixed-size pool sized to hardwareConcurrency - 1.
Always use transferables for large data. If you are passing ArrayBuffers, ImageData, or OffscreenCanvas objects, put them in the transfer list. Zero-copy is the whole point.
OffscreenCanvas frees the main thread. Move canvas rendering to a worker for jank-free animations and smooth data visualizations.
Use Comlink for complex worker APIs. It turns postMessage boilerplate into clean async function calls with full TypeScript support.
Measure before and after. The 50 ms rule is a heuristic. Profile your specific workload to confirm that worker offloading improves performance. The Performance API and Chrome DevTools Performance panel are your friends.
Service Workers are a commitment. Once registered, the browser manages their lifecycle. Cache invalidation, update logic, and scope management require careful design. Test offline behavior thoroughly.
1. Measure the main thread
Is your task blocking for 50+ ms? Use the Performance API or DevTools to find out. If not, keep it on the main thread.
2. Choose the worker type
Compute work → Dedicated. Cross-tab coordination → Shared. Offline/caching → Service Worker. Canvas rendering → Dedicated + OffscreenCanvas.
3. Build a worker pool▾
Size your pool to hardwareConcurrency - 1. Pre-create workers at app startup. Queue tasks when all workers are busy.
4. Use transferables for zero-copy
For ArrayBuffer, ImageBitmap, OffscreenCanvas — pass in the transfer list of postMessage. Detach from the sender, zero-copy to the receiver.
5. Choose Comlink or raw postMessage
Comlink for 3+ methods on a worker API. Raw postMessage for simple one-shot compute tasks. Both are valid — choose based on API surface.
6. Monitor worker health
Track pool utilization, task queue depth, worker errors, and memory usage. Terminate idle workers after timeout. Re-create crashed workers.
Tip
The best Web Worker setup is invisible. The user should never know that work was offloaded — they should just notice that the UI never janks, animations are smooth, and complex operations complete without freezing the screen. Web Workers are infrastructure, not a feature — and good infrastructure stays out of the way.