ResizeObserver
A polyfill/ponyfill entirely based on the current ResizeObserver Draft Specification.
This library observes elements and dispatches notifications when dimensions change. No polling of the DOM is required, except for when animations or transitions are active, keeping CPU and power consumption minimal.
Installation
npm i @juggle/resize-observer
Usage
import ResizeObserver from '@juggle/resize-observer';
const ro = new ResizeObserver((entries, observer) => {
console.log('Body has resized!');
observer.disconnect();
});
ro.observe(document.body);
This will use the ponyfilled version of ResizeObserver, even if the browser supports ResizeObserver natively.
Switching between native and polyfilled versions
You can check to see if the native version is available and switch between this and the polyfill to improve porformance on browsers with native support.
import ResizeObserverPolyfill from '@juggle/resize-observer';
const ResizeObserver = window.ResizeObserver || ResizeObserverPolyfill;
const ro = new ResizeObserver((entries, observer) => {
console.log('Something has resized!');
});
TypeScript Support
This library is written in TypeScript, however, it's compiled into JavaScript during release. Definition files are included in the package and should be picked up automatically to re-enable support in TypeScript projects.
Limitations
- No support for IE10 and below. IE11 is supported.
- Dynamic stylesheet changes may not be noticed and updates will occur on the next user interaction.
- Currently no support for observations when
display:none
is toggled (coming soon).