|
| 1 | +# Prever Observers over Events |
| 2 | + |
| 3 | +Some events, such as `scroll` and `resize` have traditionally caused performance issues on web pages, as they are high frequency events, firing many times per second as the user interacts with the page viewport. |
| 4 | + |
| 5 | +## Scroll vs IntersectionObserver |
| 6 | + |
| 7 | +Typically `scroll` events are used to determine if an element is intersecting a viewport, which can result in expensive operations such as layout calculations, which has a detrimental affect on UI performance. Recent developments in web standards have introduced the `IntersectionObserver`, which is a more performant mechanism for determining if an element is intersecting the viewport. |
| 8 | + |
| 9 | +```js |
| 10 | +// bad, expensive, error-prone code to determine if the element is in the viewport; |
| 11 | +window.addEventListener('scroll', () => { |
| 12 | + const isIntersecting = checkIfElementIntersects(element.getBoundingClientRect(), window.innerHeight, document.clientHeight) |
| 13 | + element.classList.toggle('intersecting', isIntersecting) |
| 14 | +}) |
| 15 | + |
| 16 | +// good - more performant and less error-prone |
| 17 | +const observer = new IntersectionObserver(entries => { |
| 18 | + for(const {target, isIntersecting} of entries) { |
| 19 | + target.classList.toggle(target, isIntersecting) |
| 20 | + } |
| 21 | +}) |
| 22 | +observer.observe(element) |
| 23 | +``` |
| 24 | + |
| 25 | +## Resize vs ResizeObserver |
| 26 | + |
| 27 | +Similarly, `resize` events are typically used to determine if the viewport is smaller or larger than a certain size, similar to CSS media break points. Similar to the `IntersectionObserver` the `ResizeObserver` also exists as a more performant mechanism for observing changes to the viewport size. |
| 28 | + |
| 29 | +```js |
| 30 | +// bad, low-performing code to determine if the element is less than 500px large |
| 31 | +window.addEventListener('resize', () => { |
| 32 | + element.classList.toggle('size-small', element.getBoundingClientRect().width < 500) |
| 33 | +}) |
| 34 | + |
| 35 | +// good - more performant, only fires when the actual elements change size |
| 36 | +const observer = new ResizeObserver(entries => { |
| 37 | + for(const {target, contentRect} of entries) { |
| 38 | + target.classList.toggle('size-small', contentRect.width < 500) |
| 39 | + } |
| 40 | +}) |
| 41 | +observer.observe(element) |
| 42 | +``` |
| 43 | + |
| 44 | +## See Also |
| 45 | + |
| 46 | +https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API |
| 47 | +https://developer.mozilla.org/en-US/docs/Web/API/Resize_Observer_API |
0 commit comments