|
| 1 | +## 🏝 What is Resize Observer API |
| 2 | + |
| 3 | +The [Resize Observer API](https://developer.mozilla.org/en-US/docs/Web/API/Resize_Observer_API) can help us listen to the change of element size and perform some actions when the size changes. For example, we can use Resize Observer API to dynamically adjust UI layout, load or unload images, etc. |
| 4 | + |
| 5 | +## 🎨 How to use the Resize Observer API |
| 6 | + |
| 7 | +Using the Resize Observer API is very simple. I'll walk you through 3 usage examples to familiarize you with the Resize Observer API. |
| 8 | + |
| 9 | +### 1. Listening for changes in element size |
| 10 | + |
| 11 | +In development projects, we usually need to **listen for changes in element size** and perform some actions when the size changes. For example, we may need to dynamically adjust the UI layout to fit a different size screen or device. The following is an example of listening for element size changes: |
| 12 | + |
| 13 | +```javascript |
| 14 | +// Create a ResizeObserver instance |
| 15 | +const observer = new ResizeObserver((entries) => { |
| 16 | + for (let entry of entries) { |
| 17 | + console.log(entry.target, entry.contentRect); |
| 18 | + |
| 19 | + // dynamically adjust the UI layout |
| 20 | + const { width, height } = entry.contentRect; |
| 21 | + // ... |
| 22 | + } |
| 23 | +}); |
| 24 | + |
| 25 | +// Listening for an element |
| 26 | +const element = document.getElementById("my-element"); |
| 27 | +observer.observe(element); |
| 28 | +``` |
| 29 | + |
| 30 | +In this example, we use the Resize Observer API to listen for changes in the size of the element with ID "my-element". In the callback function, we can get information about the size of the element and use this information to dynamically adjust the UI layout. |
| 31 | + |
| 32 | +### 2. Listening for size changes inside elements |
| 33 | + |
| 34 | +In addition to listening for changes in the size of the element itself, we can also listen for changes in the size of **the inside** of the element. For example, when the text or image inside an element changes, we may need to recalculate the size of the element and adjust the UI layout accordingly. The following is an example of listening for changes in the size of the element's internals: |
| 35 | + |
| 36 | +```javascript |
| 37 | +// Create a ResizeObserver instance |
| 38 | +const observer = new ResizeObserver((entries) => { |
| 39 | + for (let entry of entries) { |
| 40 | + console.log(entry.target, entry.contentRect); |
| 41 | + |
| 42 | + // dynamically adjust the UI layout |
| 43 | + const { width, height } = entry.contentRect; |
| 44 | + // ... |
| 45 | + } |
| 46 | +}); |
| 47 | + |
| 48 | +// listen to the internal size change of an element |
| 49 | +const element = document.getElementById("my-element"); |
| 50 | +observer.observe(element, { box: "content-box" }); |
| 51 | +``` |
| 52 | + |
| 53 | +In this example, we use the Resize Observer API to listen for size changes inside the **element** with ID "my-element". We pass an option object with the `box` property set to `content-box`, indicating that we want to listen for size changes inside the element. |
| 54 | + |
| 55 | +### 3. Using the Resize Observer API in React |
| 56 | + |
| 57 | +Of course, we can also use it in React or Vue, and we can also use third-party libraries to simplify the use of the Resize Observer API. For example, in React, you can use the `react-resize-observer` library to listen for changes in the size of elements. Here is an example of using the react-resize-observer library: |
| 58 | + |
| 59 | +```jsx |
| 60 | +import React, { useState } from "react"; |
| 61 | +import { ResizeObserver } from "@juggle/resize-observer"; |
| 62 | +import { useResizeObserver } from "react-resize-observer"; |
| 63 | + |
| 64 | +function MyComponent() { |
| 65 | + const [width, setWidth] = useState(0); |
| 66 | + const [height, setHeight] = useState(0); |
| 67 | + |
| 68 | + const onResize = (entry) => { |
| 69 | + const { width, height } = entry.contentRect; |
| 70 | + setWidth(width); |
| 71 | + setHeight(height); |
| 72 | + }; |
| 73 | + |
| 74 | + const { ref } = useResizeObserver({ onResize, polyfill: ResizeObserver }); |
| 75 | + |
| 76 | + return <div ref={ref}>My content goes here</div>; |
| 77 | +} |
| 78 | +``` |
| 79 | + |
| 80 | +In this example, we use [react-resize-observer](https://github.com/bootstarted/react-resize-observer) and [@juggle/resize-observer](https://github.com/juggle/resize-observer) libraries to listen for changes in the size of elements. We use the `useResizeObserver()` hook to create a ResizeObserver instance and update the state of the component in the callback function. |
| 81 | + |
| 82 | +## 👍 Where to use the Resize Observer API |
| 83 | + |
| 84 | +The Resize Observer API can be used in many work scenarios. For example: |
| 85 | + |
| 86 | +### 1. Responsive Layout |
| 87 | + |
| 88 | +Responsive layout\*\* can be easily implemented using the Resize Observer API. For example, when the screen size changes, we can listen to the size change of the root element and adjust the UI layout accordingly. |
| 89 | +The following is sample code implemented using the Resize Observer API: |
| 90 | + |
| 91 | +```html |
| 92 | +<! -- Responsive layout sample code --> |
| 93 | +<div class="container" id="responsive-container"> |
| 94 | + <div class="row"> |
| 95 | + <div class="col-sm-4"> |
| 96 | + <p>First column content</p> |
| 97 | + </div> |
| 98 | + <div class="col-sm-4"> |
| 99 | + <p>Second column content</p> |
| 100 | + </div> |
| 101 | + <div class="col-sm-4"> |
| 102 | + <p>Third column content</p> |
| 103 | + </div> |
| 104 | + </div> |
| 105 | +</div> |
| 106 | + |
| 107 | +<script> |
| 108 | + const container = document.getElementById("responsive-container"); |
| 109 | +
|
| 110 | + const resizeObserver = new ResizeObserver((entries) => { |
| 111 | + for (let entry of entries) { |
| 112 | + const { width } = entry.contentRect; |
| 113 | + if (width >= 768) { |
| 114 | + container.classList.add("large-device"); |
| 115 | + } else { |
| 116 | + container.classList.remove("large-device"); |
| 117 | + } |
| 118 | + } |
| 119 | + }); |
| 120 | +
|
| 121 | + resizeObserver.observe(container); |
| 122 | +</script> |
| 123 | + |
| 124 | +<style> |
| 125 | + .large-device .col-sm-4 { |
| 126 | + width: 33.33%; |
| 127 | + } |
| 128 | +</style> |
| 129 | +``` |
| 130 | + |
| 131 | +### 2. Image lazy loading |
| 132 | + |
| 133 | +Using Resize Observer API you can implement **image lazy loading**. For example, when an image element enters the visible area, we can listen to its size change and display the image after the element is fully loaded. |
| 134 | +The following is a sample code for lazy loading of images using the Resize Observer API: |
| 135 | + |
| 136 | +```html |
| 137 | +<!-- HTML --> |
| 138 | +<img data-src="https://example.com/image.jpg" alt="My image" /> |
| 139 | + |
| 140 | +<script> |
| 141 | + // JavaScript |
| 142 | + const observer = new ResizeObserver((entries) => { |
| 143 | + for (let entry of entries) { |
| 144 | + if (entry.isIntersecting) { |
| 145 | + const img = entry.target; |
| 146 | + const src = img.getAttribute("data-src"); |
| 147 | + if (src) { |
| 148 | + img.setAttribute("src", src); |
| 149 | + img.removeAttribute("data-src"); |
| 150 | + } |
| 151 | + } |
| 152 | + } |
| 153 | + }); |
| 154 | +
|
| 155 | + const images = document.querySelectorAll("img[data-src]"); |
| 156 | + images.forEach((img) => { |
| 157 | + observer.observe(img); |
| 158 | + }); |
| 159 | +</script> |
| 160 | +``` |
| 161 | + |
| 162 | +In the above code, we use the Resize Observer API to listen for changes in the size of the image element. When the image element enters the viewable area, we assign the URL in its `data-src` property to its `src` property to achieve the effect of lazy loading of the image. Also, we use the Intersection Observer API to listen to whether the image element enters the visible area. |
| 163 | + |
| 164 | +Note that in this sample code, we also need to set a `data-src` attribute for the image element, which contains the URL of the image to be loaded, so as to avoid loading all the images immediately on page load and thus improve page performance. |
| 165 | + |
| 166 | +### 3. Adaptive UI components |
| 167 | + |
| 168 | +Adaptive UI components can be easily implemented using the Resize Observer API. For example, when the number or size of elements inside a UI component changes, we can listen for the size change and adjust the UI layout accordingly. |
| 169 | + |
| 170 | +## 🧭 Resize Observer API Compatibility |
| 171 | + |
| 172 | +The Resize Observer API is a relatively new Web API and is currently only supported in modern browsers. Here is the compatibility of the Resize Observer API: |
| 173 | + |
| 174 | +- Chrome 64+ ✅ |
| 175 | +- Firefox 69+ ✅ |
| 176 | +- Safari 14.1+ ✅ |
| 177 | +- Edge 79+ ✅ |
| 178 | +- Opera 51+ ✅ |
| 179 | + |
| 180 | +Details of compatibility can be viewed at [Can I Use](https://caniuse.com/?search=Resize%20Observer%20API). |
| 181 | + |
| 182 | +## 📋 Resize Observer API Pros and Cons |
| 183 | + |
| 184 | +The following are the advantages and disadvantages of the Resize Observer API: |
| 185 | + |
| 186 | +### 1.Advantages |
| 187 | + |
| 188 | +- Can be used to detect changes in element size without polling or using other detection techniques. |
| 189 | +- It can listen to **multiple elements** for size changes and only trigger the callback function when the element size changes. |
| 190 | +- Size changes can be detected for **any element**, not limited to visible elements. |
| 191 | +- Compared to other detection techniques (such as the `window.resize` event), the Resize Observer API is more stable, as it avoids performance problems due to frequent triggering of events. |
| 192 | + |
| 193 | +### 2. Disadvantages |
| 194 | + |
| 195 | +- Not supported by all browsers, especially older browsers. |
| 196 | +- Because the Resize Observer API's callback function is executed asynchronously, it is not guaranteed to execute immediately after an element size change. |
| 197 | +- The Resize Observer API does not provide the exact size value of the element, only the size change information. If you need to get the specific size value of an element, developers need to calculate it themselves. |
| 198 | + |
| 199 | +## 🎯 Summary |
| 200 | + |
| 201 | +In this article, we introduced the basic usage of Resize Observer API and provided some sample code to help you better understand and use the API. hope this article can help you better understand and use Resize Observer API. |
| 202 | +If you want to know more information, please refer to the following references: |
| 203 | + |
| 204 | +- [MDN Web Docs: Resize Observer API](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver) |
| 205 | +- [W3C: Resize Observer](https://www.w3.org/TR/resize-observer/) |
0 commit comments