devrelm / resize-observer

Other
98 stars 12 forks source link

resize-observer

Build Status NPM Version

npm bundle size (minified + gzip)

This library aims to be a faithful implementation and ponyfill of the Resize Observer draft. An optional polyfill option exists as well.

Installation

resize-observer is available on NPM and Yarn:

> npm install resize-observer
> yarn add resize-observer

Setup

As a ponyfill/module

resize-observer does not install itself by default. As such, you can import it like any other module:

import { ResizeObserver } from 'resize-observer';

const ro = new ResizeObserver(() => console.log('resize observed!'));
ro.observe(document.body);

As a polyfill

resize-observer provides a file that can be referenced from your browser that automatically installs ResizeObserver on the global window object. Both minified and non-minified versions exist, and are found in the package under the dist/ directory:

<script src="https://github.com/devrelm/resize-observer/raw/master/node_modules/resize-observer/dist/resize-observer.js"></script>
<script type="text/javascript">
  const ro = new window.ResizeObserver(() => alert('Observing things is super cool!'));
  /* use your ResizeObserver! */
</script>

A install method is also provided to do the same within your own code:

import { install } from 'resize-observer';

install();

const ro = new window.ResizeObserver(() => alert('Observe all the things!'));
/* ... */

Note: Calling install will always overwrite window.ResizeObserver. If you'd like to only install resize-observer when it doesn't already exist, you can add a simple check before calling install:

import { install } from 'resize-observer';

if (!window.ResizeObserver) install();

/* ... */

TypeScript definitions

resize-observer is written in TypeScript. The definition files are included in the package and should be picked up automatically.