HTML Web Worker API
π Introduction to Web Workers
The Web Worker API enables running JavaScript code in background threads separate from the main UI thread. This helps keep your web app responsive by offloading heavy computations or tasks to workers. π§ β‘
>>βRun heavy scripts without freezing the UI β Web Workers to the rescue!β π¦ΈββοΈ
π What Are Web Workers?
Web Workers are JavaScript files that run in parallel to your main script, without blocking user interactions like clicks or scrolling. Communication happens via message passing.
βοΈ Creating a Basic Web Worker
Step 1: Create a worker script (worker.js):
worker.js
self.onmessage = function(event) {
const num = event.data;
// Perform a CPU-heavy task (e.g. Fibonacci)
function fibonacci(n) {
return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);
}
const result = fibonacci(num);
self.postMessage(result);
};Step 2: Use the worker in your main script:
Main script
const worker = new Worker('worker.js');
worker.postMessage(40); // Send data to worker
worker.onmessage = function(event) {
console.log('Fibonacci result:', event.data);
worker.terminate(); // Stop worker when done
};
worker.onerror = function(error) {
console.error('Worker error:', error.message);
};π§ Communication Between Main Thread and Worker
- Main thread sends messages with worker.postMessage(data).
- Worker receives messages via onmessage event handler.
- Worker sends results back with postMessage().
- Main thread listens for results with worker.onmessage.
π‘ Use Cases for Web Workers
- Complex calculations (math, data processing).
- Image or video processing.
- Fetching and parsing large data asynchronously.
- Real-time data visualization and games.
β οΈ Important Notes
- Workers run in isolated contexts β they canβt access DOM directly.
- Use worker.terminate() to stop workers and free resources.
- Transferable objects can be used to optimize data transfer between threads.
- Workers have limited access to browser APIs for security reasons.
π Useful Resources
>>βWeb Workers help build fast, smooth, and responsive web apps by harnessing parallelism.β β‘