Lesson 90 – JavaScript Web Workers
Web Workers allow JavaScript to run in the background, on a separate thread from the main execution thread. This helps prevent UI freezing, especially during heavy computations or data processing.
What are Web Workers?
- JavaScript is single-threaded by default.
- Web Workers run scripts in background threads, separate from the main UI thread.
- Useful for tasks like:
- Heavy computations
- Parsing large files
- Processing data without blocking UI
When to Use Web Workers
- Long loops or expensive calculations
- Repeated or concurrent data processing
- Keeping UI responsive during background tasks
Creating a Web Worker
- Create a separate JavaScript file for the worker (e.g.
worker.js
) - In your main script, use the
Worker()
constructor to run it.
worker.js
// This code runs in the background
self.onmessage = function(e) {
console.log('Worker received:', e.data);
let result = e.data * 2;
self.postMessage(result);
};
main.js
const worker = new Worker('worker.js');
worker.postMessage(10); // Send data to worker
worker.onmessage = function(e) {
console.log('Result from worker:', e.data);
};
Limitations
- Workers cannot manipulate the DOM directly.
- They have a separate scope from the main thread.
- You must communicate using
postMessage
.
Try Your Hand
- Create a simple HTML page.
- Set up a Web Worker to simulate a long task (like a loop).
- Display a message once the task is complete.
Summary
Feature | Description |
---|---|
Background Execution | Workers run tasks in a separate thread |
Communication | Via postMessage and onmessage |
Use Cases | Data processing, image manipulation, etc. |
Limitation | Cannot access DOM directly |