HTML Web Workers
Subject: html
βοΈ HTML Web Workers
HTML Web Workers let you run JavaScript in the background thread, separate from the main UI thread. This allows heavy processing without freezing or slowing down the web page.
Theyβre useful when:
- Performing CPU-intensive tasks
- Parsing large data
- Running real-time computations
π§ What is a Web Worker?
A Web Worker is a separate JavaScript file that runs in parallel to your main JS code:
- No access to DOM or
window
- Communicates via
postMessage()
andonmessage
- Doesnβt block UI or input events
π When to Use Web Workers
Use Web Workers when you need to:
- Do large calculations
- Fetch and process big data sets
- Offload heavy logic from the main thread
- Improve app responsiveness
π οΈ How to Use Web Workers
πΉ Step 1: Create the Worker File
πΉ Step 2: Use It in HTML
π Communication Flow
- Main β Worker:
worker.postMessage(data)
- Worker β Main:
postMessage(result)
andworker.onmessage
π« Limitations of Web Workers
- β Cannot access the DOM
- β Cannot use
window
,document
,alert()
, etc. - β Can use AJAX, timers, and import scripts
π Types of Web Workers
Type | Description |
---|---|
Dedicated Worker | One page uses it privately |
Shared Worker | Can be accessed by multiple pages/scripts |
Service Worker | Handles caching, offline, background sync |
π§ Key Takeaways
- Web Workers allow you to run JS code off the main thread
- Ideal for long-running or computationally heavy operations
- Communicate using
postMessage()
/onmessage
- Cannot access the DOM or browser-specific APIs
- Improves UI responsiveness in complex apps
Advertisement Slot 1
Advertisement Slot 2