Resize Observer MiniLoading saved progress…

Resize Observer Mini

ResizeObserver tells you when an element's box changes size — the modern way to build responsive components that react to their own dimensions, not just the window. Before it existed, the only portable trick was to poll: on a timer, measure each watched element and fire when its width or height moved. Rebuilding that fallback shows what the native, layout-synced observer buys you — and what a poll loop costs.

Implement resizeObserverMini(callback, options) with observe, unobserve, and disconnect, driving change detection off a setInterval. See MDN: ResizeObserver.

Signature

function resizeObserverMini(callback, options) {
  return { observe, unobserve, disconnect };
}
// callback(entries, observer); entry = { target, contentRect: { width, height } }

Examples

const ro = resizeObserverMini((entries) => {
  for (const e of entries) layout(e.target, e.contentRect);
}, { interval: 100 });

ro.observe(panel);   // fires an initial entry with panel's size
// ...panel grows; on the next tick the callback runs with the new size
ro.disconnect();     // clears the timer

Notes

  • Measure and remember — record each element's { width, height } (from getBoundingClientRect) and compare on every tick.
  • Fire on change only — report an element when either dimension differs from its stored size, then update the record.
  • Initial entryobserve(el) delivers the current size immediately, like the native observer.
  • Timer hygiene — start the interval on the first observe; clear it in disconnect and when the last element is unobserved, so an idle observer isn't polling forever.
Loading editor…