Web Workers come in several types, each suitable for different use cases.
1. Dedicated Worker
Characteristics
- Exclusively owned by the page or script that created it
- One-to-one relationship: A Dedicated Worker can only be used by one script
- The most commonly used Worker type
Creation Method
javascript// Create from external file const worker = new Worker('worker.js'); // Create from Blob URL (inline Worker) const workerCode = ` self.onmessage = function(e) { self.postMessage(e.data * 2); }; `; const blob = new Blob([workerCode], { type: 'application/javascript' }); const worker = new Worker(URL.createObjectURL(blob));
Use Cases
- Background computation tasks for single pages
- Image processing
- Data encryption/decryption
- Complex mathematical calculations
2. Shared Worker
Characteristics
- Can be shared by multiple pages or scripts
- Many-to-many relationship: Multiple scripts can connect to the same Shared Worker
- Suitable for cross-tab communication and state sharing
Creation Method
javascript// Create Shared Worker const sharedWorker = new SharedWorker('shared-worker.js'); // Connect to Worker sharedWorker.port.start(); // Send message sharedWorker.port.postMessage('Hello'); // Receive message sharedWorker.port.onmessage = function(event) { console.log('Received:', event.data); };
Shared Worker Internal Implementation
javascript// shared-worker.js const connections = []; self.onconnect = function(event) { const port = event.ports[0]; connections.push(port); port.onmessage = function(e) { // Broadcast message to all connections connections.forEach(conn => { conn.postMessage(e.data); }); }; port.start(); };
Use Cases
- Multi-tab state synchronization
- Cross-window communication
- Shared data caching
- Collaborative editing applications
3. Service Worker
Characteristics
- Acts as a network proxy to intercept and handle network requests
- Runs independently of page lifecycle
- Used to implement offline functionality and push notifications
- Must run in HTTPS environment (localhost is an exception)
Registration Method
javascript// Register Service Worker if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/service-worker.js') .then(function(registration) { console.log('Service Worker registered:', registration); }) .catch(function(error) { console.log('Registration failed:', error); }); }
Service Worker Implementation
javascript// service-worker.js const CACHE_NAME = 'my-cache-v1'; const urlsToCache = [ '/', '/styles/main.css', '/script/main.js' ]; // Install event self.addEventListener('install', function(event) { event.waitUntil( caches.open(CACHE_NAME) .then(function(cache) { return cache.addAll(urlsToCache); }) ); }); // Intercept requests self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request) .then(function(response) { if (response) { return response; } return fetch(event.request); }) ); });
Use Cases
- PWA (Progressive Web Apps)
- Offline caching
- Background synchronization
- Push notifications
- Network request optimization
4. Comparison of Worker Types
| Feature | Dedicated Worker | Shared Worker | Service Worker |
|---|---|---|---|
| Scope | Single page | Multiple pages shared | Global proxy |
| Lifecycle | Destroyed with page | Destroyed when all connections closed | Runs independently |
| DOM Access | ❌ | ❌ | ❌ |
| Network Requests | ❌ | ❌ | ✅ |
| HTTPS Required | ❌ | ❌ | ✅ |
| Communication | postMessage | port.postMessage | postMessage + fetch |
5. Other Worker Types
AudioWorklet
- Used for audio processing
- Runs in audio rendering thread
- Provides more precise audio processing capabilities
javascriptconst audioContext = new AudioContext(); audioContext.audioWorklet.addModule('audio-processor.js') .then(() => { const workletNode = new AudioWorkletNode(audioContext, 'audio-processor'); });
OffscreenCanvas
- Canvas rendering in Worker
- Improves complex graphics rendering performance
javascriptconst worker = new Worker('canvas-worker.js'); const offscreen = canvas.transferControlToOffscreen(); worker.postMessage({ canvas: offscreen }, [offscreen]);
Selection Recommendations
- Dedicated Worker: Most background computation tasks
- Shared Worker: Need to share state across tabs
- Service Worker: Need offline functionality or network request control
- AudioWorklet: Audio processing related
- OffscreenCanvas: Complex Canvas rendering