Web Workers
Web Workers allow running JavaScript in background threads, preventing UI blocking during heavy computations.
- Dedicated Workers: Single background thread
- Shared Workers: Multiple tabs/windows can share
- Service Workers: For offline capabilities (covered separately)
- Communication via message passing
- No DOM access (workers run in isolated context)
🧮 Worker Demo
Higher values = more computation
Status: Idle
⚡ Shared Array Buffer Demo
SharedArrayBuffer allows sharing memory between main thread and workers. Requires HTTPS and proper headers.
📋 Worker Limitations
- ❌ No access to DOM
- ❌ No access to window object
- ❌ No access to document object
- ✅ Can use XMLHttpRequest/Fetch
- ✅ Can use WebSockets
- ✅ Can use IndexedDB
- ✅ Can import scripts
📝 Code Example
JavaScript Editor
Best Practices
- Use workers only for CPU-intensive tasks
- Always terminate workers when done to free memory
- Keep message payloads small (use Transferable Objects for large data)
- Handle worker errors gracefully
- Consider using a worker pool for multiple tasks
- Use SharedArrayBuffer only when necessary (security considerations)