乐闻世界logo
搜索文章和话题

What is Web Worker and how does it improve web performance?

2月21日 15:11

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

  1. Big Data Processing: Processing large arrays, JSON data
  2. Complex Computation: Image processing, encryption/decryption, physics simulation
  3. Background Tasks: Periodic checks, data synchronization
  4. 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
标签:Web Worker