Web Worker is a mechanism provided by HTML5 for running JavaScript in background threads. It allows time-consuming tasks to be executed without blocking the main thread, thereby improving user experience.
Core Concepts
Web Workers run in independent threads, executing in parallel with the main thread. This means:
- Independent Execution Environment: Workers have their own global object, not window, but DedicatedWorkerGlobalScope or SharedWorkerGlobalScope
- No DOM Access: Workers cannot directly access DOM, document, window, and other objects
- Message Communication: Communicate with the main thread through postMessage() and onmessage events
- Same-Origin Policy: Worker scripts must be same-origin with the main page
Basic Usage
javascript// Main thread creates Worker const worker = new Worker('worker.js'); // Send message to Worker worker.postMessage({ data: 'Hello from main thread' }); // Receive message from Worker worker.onmessage = function(event) { console.log('Received from worker:', event.data); }; // worker.js self.onmessage = function(event) { const result = performHeavyComputation(event.data); self.postMessage(result); };
Use Cases
- Big Data Processing: Processing large arrays, JSON data
- Complex Computation: Image processing, encryption/decryption, physics simulation
- Background Tasks: Periodic checks, data synchronization
- Real-time Data Processing: Video/audio processing, WebSocket message processing
Limitations
- Cannot access DOM
- Cannot use certain APIs (such as localStorage)
- Same-origin restrictions
- Creating Workers has some performance overhead