Understanding the Browser’s Four Built-In Multithreading APIs
Modern browsers provide four multithreading mechanisms — Web Worker, Shared Worker, Service Worker, and Worklet — each running on different browser threads. Although JavaScript itself is single‑threaded, these APIs enable parallel computation, background tasks, offline caching, and real-time rendering.
1. Why Workers Enable Multithreading
JavaScript runs on a single thread, but browsers use a multi-process architecture. Worker threads are isolated from the main thread, communicate via message passing, avoid UI blocking, and have thread limits.
2. Overview of the Four Worker Types
| Worker Type | Purpose | Thread | Use Case |
|---|---|---|---|
| Web Worker | CPU-heavy tasks | Worker thread pool | Sorting, cryptography |
| Shared Worker | Shared state across tabs | Shared worker thread | Multi-tab sync |
| Service Worker | Offline caching and request control | Background thread | PWAs, offline apps |
| Worklet | Real-time rendering | Rendering pipeline | CSS animation, audio processing |
3. Web Worker — Heavy Computation
// main.js
const worker = new Worker('sort-worker.js');
worker.postMessage([5, 1, 3]);
worker.onmessage = (e) => {
console.log('Sorted:', e.data);
worker.terminate();
};// sort-worker.js
self.onmessage = (e) => {
const sorted = e.data.sort((a, b) => a - b);
self.postMessage(sorted);
self.close();
};4. Shared Worker — Cross-Tab State Sync
// sync-worker.js
const ports = [];
let state = { isLogin: false };
self.onconnect = (e) => {
const port = e.ports[0];
ports.push(port);
port.onmessage = (msg) => {
if (msg.data.type === 'LOGIN') {
state = msg.data.data;
ports.forEach(p => p.postMessage(state));
}
};
};5. Service Worker — Offline Proxy
// sw.js
const CACHE = 'v1';
self.addEventListener('install', (e) => {
e.waitUntil(
caches.open(CACHE).then(c => c.addAll(['/','/index.html']))
);
});6. Worklet — Rendering Pipeline Logic
// bounce-worklet.js
class BounceWorklet {
process(inputs, outputs) {
const t = inputs[0][0];
const y = Math.sin(t * Math.PI);
outputs[0].value = `translateY(${300 * (1 - y)}px)`;
}
}
registerAnimator('bounce', BounceWorklet);7. Combined Multi‑Worker Architecture
A real-world dashboard may combine all four Worker types to achieve smooth rendering, offline use, cross‑tab sync, and fast data parsing.
8. Using self in Workers
Workers use self instead of window and cannot access the DOM. They can only perform non-UI tasks.
9. Production Considerations
Workers require explicit error handling, careful cleanup, same-origin script loading, and performance balancing to avoid overhead.
Conclusion
Each Worker type solves a different class of performance problems. Understanding how they differ enables developers to build fast, robust, non-blocking web applications.