Resize Observer API

Questo contenuto viene visualizzato in inglese perché non è ancora disponibile una versione tradotta nella lingua selezionata. Aiutaci a tradurre questo articolo!

The Resize Observer API provides a performant mechanism by which code can monitor an element for changes to its size, with notifications being delivered to the observer each time the size changes.

Concepts and usage

There are a whole raft of use cases for responsive design techniques (and others besides) that respond to changes in an element's size, but previously their implementations have often been hacky and/or brittle.

For example, media queries / window.matchMedia are great for updating layouts at specific points when the viewport changes sizes, but what it you want to change layout in response to a specific element's size changing, which isn't the outer container?

To achieve this, a limited solution would be to listen to changes to a suitable event that hints at the element you are interested in changing size (e.g. the window resize event), then figure out what the new dimensions or other features of the element after a resize using Element.getBoundingClientRect or Window.getComputedStyle, for example.

Such a solution tends to only work for limited use cases, be bad for performance (continually calling the above methods would result in a big performance hit), and often won't work when the browser window size is not changed.

The Resize Observer API provides a solution to exactly these kinds of problems, and more besides, allowing you to easily observe and respond to changes in the size of an element’s content or border box in a performant way. If provides a JavaScript solution to the often-discussed lack of element queries in the web platform.

Usage is simple, and pretty much the same as other observers, such as Performance Observer or Intersection Observer — you create a new ResizeObserver object using the ResizeObserver() constructor, then use ResizeObserver.observe() to make it look for changes to a specific element's size. A callback function set up inside the constructor then runs every time the size changes, providing access to the new dimensions and allowing you to do anything you like in response to those changes.

Interfaces

ResizeObserver
Provides the ability to register new observers and to start and stop observing elements.
ResizeObserverEntry
Describes a single element which has been resized, identifying the element and its new size.

Examples

You find a couple of simple examples on our GitHub repo:

  • resize-observer-border-radius.html (see source): A simple example with a green box, sized as a percentage of the viewport size. When the viewport size is changed, the box's rounded corners change in proportion to the size of the box. We could just implement this using border-radius with a percentage, but that quickly leads to ugly-looking elliptical corners, whereas the above solution gives you nice square corners that scale with the box size.
  • resize-observer-text.html (see source): Here we use the resize observer to change the font-size of a header and paragraph as a slider’s value is changed causing the containing <div> to change width. This shows that you can respond to changes in an element’s size, even if they have nothing to do with the viewport.

The code will usually follow this kind of pattern (taken from resize-observer-border-radius.html):

const resizeObserver = new ResizeObserver(entries => {
  for (let entry of entries) {
    if(entry.contentBoxSize) {
      entry.target.style.borderRadius = Math.min(100, (entry.contentBoxSize.inlineSize/10) +
                                                      (entry.contentBoxSize.blockSize/10)) + 'px';
    } else {
      entry.target.style.borderRadius = Math.min(100, (entry.contentRect.width/10) +
                                                      (entry.contentRect.height/10)) + 'px';
    }
  }
});

resizeObserver.observe(document.querySelector('div'));

Specifications

Specification Status Comment
Resize Observer Editor's Draft Initial definition.

Browser compatibility

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
ResizeObserverChrome Full support 64Edge No support NoFirefox Full support 69IE No support NoOpera Full support 51Safari No support NoWebView Android Full support 64Chrome Android Full support 64Firefox Android No support NoOpera Android Full support 47Safari iOS No support NoSamsung Internet Android Full support Yes
ResizeObserver() constructorChrome Full support 64Edge No support NoFirefox Full support 69IE No support NoOpera Full support 51Safari No support NoWebView Android Full support 64Chrome Android Full support 64Firefox Android No support NoOpera Android Full support 47Safari iOS No support NoSamsung Internet Android Full support Yes
disconnectChrome Full support 64Edge No support NoFirefox Full support 69IE No support NoOpera Full support 51Safari No support NoWebView Android Full support 64Chrome Android Full support 64Firefox Android No support NoOpera Android Full support 47Safari iOS No support NoSamsung Internet Android Full support Yes
observeChrome Full support 64Edge No support NoFirefox Full support 69IE No support NoOpera Full support 51Safari No support NoWebView Android Full support 64Chrome Android Full support 64Firefox Android No support NoOpera Android Full support 47Safari iOS No support NoSamsung Internet Android Full support Yes
unobserveChrome Full support 64Edge No support NoFirefox Full support 69IE No support NoOpera Full support 51Safari No support NoWebView Android Full support 64Chrome Android Full support 64Firefox Android No support NoOpera Android Full support 47Safari iOS No support NoSamsung Internet Android Full support Yes

Legend

Full support  
Full support
No support  
No support

See also