Web Workers and Observer APIs
Run heavy work off the main thread with Web Workers, and react efficiently to visibility, size and DOM changes with observers.
Advanced · about 4 hours · difficulty 3/5
Learn first: The Event Loop, JavaScript Loading and Runtime Performance
JavaScript on a page runs on one main thread shared with rendering and input handling. Two families of APIs help keep it responsive: workers move computation elsewhere, and observers replace expensive polling and scroll handlers.
Web Workers
A dedicated worker runs a script in a separate thread: new Worker(new URL("./worker.ts", import.meta.url), { type: "module" }). It has no DOM access; you exchange messages with postMessage and onmessage. Data is copied with structured cloning, or transferred (for ArrayBuffers) to avoid copying.
- Good uses: parsing large files, image processing, search indexes, diffing, cryptography, heavy data transforms.
- Comlink wraps messaging so a worker feels like calling async functions.
- Shared workers serve several tabs; service workers are a different kind, covered in the PWA topic.
Observer APIs
- IntersectionObserver: notifies when an element enters or leaves the viewport. Use it for lazy loading, infinite scroll, analytics impressions and scroll-triggered animation, instead of listening to
scroll. - ResizeObserver: reacts to an element's size changes (charts, responsive components) rather than only the window's.
- MutationObserver: watches DOM changes, useful for integrating third-party widgets.
- PerformanceObserver: reads performance entries such as long tasks and layout shifts.
Other handy platform APIs
requestAnimationFrame for visual updates, requestIdleCallback for low-priority work, the Page Visibility API to pause work in hidden tabs, and Clipboard, Geolocation and Share APIs behind permissions.
Good enough to move on
You can move a CPU-heavy task into a worker and keep the UI smooth, and replace a scroll listener with IntersectionObserver for infinite scrolling.
Key concepts
- Dedicated Web Workers
- postMessage and transferable objects
- Comlink
- IntersectionObserver
- ResizeObserver
- MutationObserver
- requestAnimationFrame and requestIdleCallback
- Page Visibility API
Mini project
Build a CSV explorer that parses a 50 MB file in a Web Worker with progress updates, renders rows with infinite scroll via IntersectionObserver and resizes its chart with ResizeObserver.
Check yourself
Why can a Web Worker not update the DOM directly, and how does it send results back?
Free resources
- Using Web Workers (MDN)
- Intersection Observer API (MDN)
- Resize Observer API (MDN)