A minimal library which polyfills the ResizeObserver API and is entirely based on the latest Draft Specification.
It immediately detects when an element resizes and provides accurate sizing information back to the handler. Check out the Example Playground for more information on usage and performance.
The latest Resize Observer specification is not yet finalised and is subject to change.Any drastic changes to the specification will bump the major version of this library, as there will likely be breaking changes. Check the release notes for more information.
npm i @juggle/resize-observer
import { ResizeObserver } from '@juggle/resize-observer';
const ro = new ResizeObserver((entries, observer) => {
console.log('Body has resized!');
observer.disconnect(); // Stop observing
});
ro.observe(document.body); // Watch dimension changes on body
This will use the ponyfilled version of ResizeObserver, even if the browser supports ResizeObserver natively.
import { ResizeObserver } from '@juggle/resize-observer';
const ro = new ResizeObserver((entries, observer) => {
console.log('Elements resized:', entries.length);
entries.forEach((entry, index) => {
const { inlineSize: width, blockSize: height } = entry.contentBoxSize[0];
console.log(`Element ${index + 1}:`, `${width}x${height}`);
});
});
const els = document.querySelectorAll('.resizes');
[...els].forEach(el => ro.observe(el)); // Watch multiple!
The latest standards allow for watching different box sizes. The box size option can be specified when observing an element. Options include border-box
, device-pixel-content-box
and content-box
(default).
import { ResizeObserver } from '@juggle/resize-observer';
const ro = new ResizeObserver((entries, observer) => {
console.log('Elements resized:', entries.length);
entries.forEach((entry, index) => {
const [size] = entry.borderBoxSize;
console.log(`Element ${index + 1}:`, `${size.inlineSize}x${size.blockSize}`);
});
});
// Watch border-box
const observerOptions = {
box: 'border-box'
};
const els = document.querySelectorAll('.resizes');
[...els].forEach(el => ro.observe(el, observerOptions));
From the spec:
The box size properties are exposed as sequences in order to support elements that have multiple fragments, which occur in multi-column scenarios. However the current definitions of content rect and border box do not mention how those boxes are affected by multi-column layout. In this spec, there will only be a single ResizeObserverSize returned in the sequences, which will correspond to the dimensions of the first column. A future version of this spec will extend the returned sequences to contain the per-fragment size information.
contentRect
)Early versions of the API return a contentRect
. This is still made available for backwards compatibility.
import { ResizeObserver } from '@juggle/resize-observer';
const ro = new ResizeObserver((entries, observer) => {
console.log('Elements resized:', entries.length);
entries.forEach((entry, index) => {
const { width, height } = entry.contentRect;
console.log(`Element ${index + 1}:`, `${width}x${height}`);
});
});
const els = document.querySelectorAll('.resizes');
[...els].forEach(el => ro.observe(el));
You can check to see if the native version is available and switch between this and the polyfill to improve performance on browsers with native support.
import { ResizeObserver as Polyfill } from '@juggle/resize-observer';
const ResizeObserver = window.ResizeObserver || Polyfill;
// Uses native or polyfill, depending on browser support.
const ro = new ResizeObserver((entries, observer) => {
console.log('Something has resized!');
});
To improve this even more, you could use dynamic imports to only load the file when the polyfill is required.
(async () => {
if ('ResizeObserver' in window === false) {
// Loads polyfill asynchronously, only if required.
const module = await import('@juggle/resize-observer');
window.ResizeObserver = module.ResizeObserver;
}
// Uses native or polyfill, depending on browser support.
const ro = new ResizeObserver((entries, observer) => {
console.log('Something has resized!');
});
})();
Browsers with native support may be behind on the latest specification.Use
entry.contentRect
when switching between native and polyfilled versions.
Resize Observers have inbuilt protection against infinite resize loops.
If an element's observed box size changes again within the same resize loop, the observation will be skipped and an error event will be dispatched on the window. Elements with undelivered notifications will be considered for delivery in the next loop.
import { ResizeObserver } from '@juggle/resize-observer';
const ro = new ResizeObserver((entries, observer) => {
// Changing the body size inside of the observer
// will cause a resize loop and the next observation will be skipped
document.body.style.width = '50%';
});
// Listen for errors
window.addEventListener('error', e => console.log(e.message));
// Observe the body
ro.observe(document.body);
Notifications are scheduled after all other changes have occurred and all other animation callbacks have been called. This allows the observer callback to get the most accurate size of an element, as no other changes should occur in the same frame.
To prevent constant polling, every frame. The DOM is queried whenever an event occurs which could cause an element to change its size. This could be when an element is clicked, a DOM Node is added, or, when an animation is running.
To cover these scenarios, there are two types of observation. The first is to listen to specific DOM events, including resize
, mousedown
and focus
to name a few. The second is to listen for any DOM mutations that occur. This detects when a DOM node is added or removed, an attribute is modified, or, even when some text has changed.
This allows for greater idle time, when the application itself is idle.
:hover
, :active
and :focus
.Chrome | Safari | Firefox | Opera | Edge | Edge 12-18 | IE11 IE 9-10 (with polyfills)** |
Chrome | Safari | Firefox | Opera | Opera Mini | Edge | Samsung Internet |
*If other interaction occurs, changes will be detected.
**IE10 requires additional polyfills for WeakMap
, MutationObserver
and devicePixelRatio
. IE9 requires IE10 polyfills plus requestAnimationFrame
. For more information, see issue here.
Resize Observer是一个新的JavaScript API,与Intersection Observer API、Mutation Observer等其他观察者API非常相似。 它允许在尺寸发生变化时通知元素。 基本用法 使用Resize Observer非常简单,只需实例化一个新的ResizeObserver对象并传入一个回调函数,该函数接收观察到的条目 const myObserve
这是resize-observer-polyfill源码解读的第三章,在上一章的末尾,由于ResizeObserverController类内部没有调用自身内部的函数,并且controller作为单例参数被传入到了ResizeObserverSPI内。所以对于controller的操作,也都存在与SPI中。 先看看完整代码 import {Map} from './shims/es6-collec
书接上文,我们已经看完了ResizeObserver类,但该类的constructor中使用了两个外部导入的类,分别是ResizeObserverController和ResizeObserverSPI,先来看看ResizeObserverController的完整源码 import isBrowser from './utils/isBrowser.js'; import throttle fr
1、安装resize-observer-polyfill npm install resize-observer-polyfill --save-dev 2、在utils文件夹下的index.ts引入使用 import ResizeObserver from 'resize-observer-polyfill' /** * @description 监听dom的宽高变化 * @param {E
1、作用 可以监听圆度宽度与高度的变化 2、使用步骤 第一步 安装 npm i resize-observer-polyfill --save-dev 监听元素宽高的变化
在上一章的最后,我们分析到了ResizeObserverSPI的broadcastActive方法。 /** * Invokes initial callback function with a list of ResizeObserverEntry * instances collected from active resize observations. * * @returns {v
解决Angular12报错(resize-observer-polyfill) TS2717:Property contentRect must be of type DOMRectReadOnly 错误内容: 升级到Angular 12后,Angular UI 组件库 ng-zorro-antd 引用的 resize-observer-polyfill 库报错: Property content
对于页面监听我们常用窗口的resize事件window.addEventListener(“resize”, watchWindowSize); 对吧,这个总的来说,还是影响页面性能,而且在页面销毁的时候,还需要手动把这个监听事件清楚掉,一但忘了,轻则页面卡顿,重则内存泄漏,对吧,所以前端优化任重道远… 今天说的是ResizeObserver 使用ResizeObserver对单个元素进行大小监听
上地址github: https://github.com/que-etc/resize-observer-polyfill demo: https://que-etc.github.io/resize-observer-polyfill/
此函数返回具有指定大小的新数组。 如果新大小大于原始大小,则包含原始条目的重复副本。 该函数采用以下参数。 numpy.resize(arr, shape) Where, Sr.No. 参数和描述 1 arr 要调整大小的输入数组 2 shape 生成的数组的新形状 例子 (Example) import numpy as np a = np.array([[1,2,3],[4,5,6]])
更新画布大小。当容器改变大小时,应调用此方法。 参数 名称 类型 默认值 描述 opts Object 宽高配置项 opts.width number|string 'auto' 宽度,设为 'auto' 与设为 null 或 undefined 的效果相同,相当于自动获取容器宽度以改变画布宽度。 opts.height number|string 'auto' 高度,设为 'auto' 与设为
描述 (Description) Resize able函数可以与JqueryUI中的交互一起使用。 可以在任何DOM元素上启用此功能调整功能。使用光标抓住右边框或底部边框并拖动到所需的宽度或高度。 语法 (Syntax) 以下是使用可拖动的简单语法 - $( "#resizable" ).resizable(); 例子 (Example) 以下是一个简单的示例,显示了Resize-able的用
Resize Magic 是一个程序用来对图片进行缩放,使用高质量的算法,可用来对图像进行批处理,并保留原有的 EXIF 和 ICC 色彩空间数据信息,同时商业版还提供了一个 PhotoShop 的插件。 一些实例:http://www.fsoft.it/imaging/en/Esempi.htm
描述 (Description) 调整大小操作会将width, height, data-width and data-height属性设置为“img”/“video”或“a”标记。 这样,您的图像将以请求的大小显示。 例子 (Example) ![](video.mp4?resize = 400, 220) 输出 (Output) 上面的代码将生成以下输出&
Angular Resize Event Angular 12 directive for detecting changes of an element size. It is as simple as: <div (resized)="onResized($event)"></div> It internally uses browser native ResizeObserver. Ther