Search code examples
javascriptdomresizeaddeventlistenerwindow-resize

why was `ResizeObserver` introduced to listen to resize changes and not a simpler Element.prototype.addEventListener('resize', callback)


I'm a bit surprised that in order to listen to changes on elements dimensions (not window Object) we have to use a new interface called ResizeObserver. While it seems to do the job pretty well; it seems a bit of a departure from other element related events that can be consumed by just adding a listener.

Take for example adding an event listener to listen for the mouseover event

document.querySelector('#ele').addEventListener('mouseover', callback);

Why not simply add a new listener to the resize event on the elements?

document.querySelector('#ele').addEventListener('resize', callback);

Is it to avoid conflicts with the window resize event? If so, why not just call it differently

document.querySelector('#ele').addEventListener('elementResize', callback);

I'm aware it is easy to create a helper method to simplify the usage of the ResizeObserver. Something like that can be as simple to use as the original addEventListener approach

export const getResizeObserver = ( ele, onResize ) => {
  let obs;

  const observerInterface = {
    stop: () => { obs.unobserve( ele ); obs.disconnect() },
  };

  obs = new ResizeObserver( entries => {
    for ( const entry of entries ) {
      onResize && onResize( entry.contentRect );
    }
  } );

  obs.observe( ele );

  return observerInterface;
};

// usage to add the listener
const obs = getResizeObserver(document.querySelector('#ele'), callback);
// later to remove the listener
obs.stop();

In any case, Is there any reason, besides just api preferences and the fact that several elements can share the observer instance, that makes the ResizeObserver approach better than the addEventListener approach?


Solution

  • This was proposed, but Chrome decided to ship this using the Observer model, seemingly mostly because it was 10x faster than an implementation based on events https://groups.google.com/a/chromium.org/forum/#!topic/blink-dev/z6ienONUb5A

    Now why that’s true, I don’t know.