Resize Observer is a new JavaScript API that’s very similar to other observer APIs like the Intersection Observer API. It allows for elements to be notified when their size changes.
The most frequent reason for an element’s size to change is when the viewport is resized or the device’s direction changes between portrait and landscape. Up until this point, we’ve had to rely on the global window.resize
event to listen for resize events and check if certain elements have changed size. This can easily lead to performance problems due to the large amount of triggered event. In other words, using window.resize
is often wasteful because it informs us of every viewport size change, not just when an element’s size actually changes.
There’s also another use case for the Resize Observer API that the window’s resize event can’t help us with: when elements are added or removed from the DOM dynamically, influencing the size of the parent element. This is more and more frequent with modern single-page apps.
Using Resize Observer is as simple as instantiating a new ResizeObserver object and passing-in a callback function that receives the entries that are observed.
With each entry, we get an object with a contentRect and a target property. The target is the DOM element itself, and contentRect is an object with the following properties: width, height, x, y, top, right, bottom and left.
Unlike with an element’s getBoundingClientRect, contentRect’s values for width and height don’t include padding values. contentRect.top
is the element’s top padding and contentRect.left
is the element’s left padding.
const myObserver = new ResizeObserver(entries => {
entries.forEach(entry => {
console.log('width', entry.contentRect.width);
console.log('height', entry.contentRect.height);
});
});
const someEl = document.querySelector('.some-element');
myObserver.observe(someEl);
Browser support right now is pretty bad, with only Chrome 64+ supporting Resize Observer out of the box. Thankfully, there’s a polyfill we can use in the mean time. The polyfill is based on the MutationObserver API.