ResizeObserver & IntersectionObserver APIs
ResizeObserver & IntersectionObserver APIs in Modern JavaScript
Historically, detecting when an element became visible on screen or changed dimensions required attaching expensive scroll and resize listeners to window with heavy debouncing. The modern standard Web APIs—IntersectionObserver and ResizeObserver—perform these calculations directly in the browser's native compositing pipeline with high efficiency.
1. IntersectionObserver: Visibility & Viewport Tracking
IntersectionObserver detects when a target element intersects with an ancestor element or the top-level document viewport.
High-Performance Lazy-Loading Images:
2. Infinite Scrolling with IntersectionObserver
Instead of calculating scroll height mathematics, place an empty "sentinel" <div> at the bottom of the feed:
3. ResizeObserver: Element-Level Responsive Queries
While CSS @media queries only evaluate the entire browser window width, modern component design requires styling widgets based on their own container width (Container Queries). ResizeObserver monitors an individual element's box model:
4. Comparison Matrix
| Feature | IntersectionObserver | ResizeObserver |
|---|---|---|
| Monitors | Relative visibility / viewport overlap | Element boundary / contentRect size changes |
| Key Use Cases | Lazy loading images, infinite scroll, ad viewability | Container queries, responsive charts, canvas redraws |
| Performance | Off-main-thread compositing engine | Batched before paint; prevents layout loops |
Practice Quiz
IndexedDB Architecture & Transactions
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| MutationObserver API | IndexedDB Architecture & Transactions |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.