Web Worker and SharedWorker Detection
Detect Web Worker and SharedWorker support for running JavaScript in background threads. Covers worker types, communication patterns, and performance benefits.
Workers
Detailed Explanation
Web Worker Detection
Web Workers enable running JavaScript in background threads, preventing heavy computation from blocking the UI thread. They are fundamental to responsive web applications.
Detection
const hasWebWorker = typeof Worker !== 'undefined';
const hasSharedWorker = typeof SharedWorker !== 'undefined';
Worker Types
| Type | Scope | Sharing | Use Case |
|---|---|---|---|
| Dedicated Worker | Single page | No | Heavy computation |
| Shared Worker | Multiple tabs | Yes | Shared state across tabs |
| Service Worker | All pages in scope | Yes | Offline, push, caching |
Creating a Dedicated Worker
// main.js
const worker = new Worker('worker.js');
worker.postMessage({ data: largeArray });
worker.onmessage = (e) => {
console.log('Result:', e.data);
};
// worker.js
onmessage = (e) => {
const result = heavyComputation(e.data);
postMessage(result);
};
Inline Workers with Blob URLs
const code = \`
onmessage = (e) => {
const result = e.data.map(x => x * 2);
postMessage(result);
};
\`;
const blob = new Blob([code], { type: 'text/javascript' });
const worker = new Worker(URL.createObjectURL(blob));
Transferable Objects
For large data, use Transferable objects to avoid copying:
const buffer = new ArrayBuffer(1024 * 1024);
worker.postMessage({ buffer }, [buffer]);
// buffer is now empty in the main thread
Limitations
- No DOM access (no
document,window, etc.) - Limited API availability (no
localStorage,alert, etc.) - Communication overhead for small messages
- Module workers (
type: 'module') support varies
Use Case
Used for CPU-intensive operations like image processing, data parsing, encryption, sorting large datasets, and running WebAssembly modules off the main thread. Also useful for background data fetching and caching strategies.