Skip to content

Commit

Permalink
fix(core): wrap resize observer callback in requestAnimationFrame (#5441
Browse files Browse the repository at this point in the history
)

Fast browser window resize produces `Error: ResizeObserver loop limit
exceeded`. The error isn't visible in browser console, doesn't affect
functionality, but degrades performance of slider. Solution is taken
from https://stackoverflow.com/a/58701523/17278571.

Fixes #5440
  • Loading branch information
jaksenko authored Feb 10, 2022
1 parent 3bc27a4 commit 0567641
Showing 1 changed file with 20 additions and 14 deletions.
34 changes: 20 additions & 14 deletions src/core/modules/resize/resize.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { getWindow } from 'ssr-window';
export default function Resize({ swiper, on, emit }) {
const window = getWindow();
let observer = null;
let animationFrame = null;

const resizeHandler = () => {
if (!swiper || swiper.destroyed || !swiper.initialized) return;
Expand All @@ -13,26 +14,31 @@ export default function Resize({ swiper, on, emit }) {
const createObserver = () => {
if (!swiper || swiper.destroyed || !swiper.initialized) return;
observer = new ResizeObserver((entries) => {
const { width, height } = swiper;
let newWidth = width;
let newHeight = height;
entries.forEach(({ contentBoxSize, contentRect, target }) => {
if (target && target !== swiper.el) return;
newWidth = contentRect
? contentRect.width
: (contentBoxSize[0] || contentBoxSize).inlineSize;
newHeight = contentRect
? contentRect.height
: (contentBoxSize[0] || contentBoxSize).blockSize;
animationFrame = window.requestAnimationFrame(() => {
const { width, height } = swiper;
let newWidth = width;
let newHeight = height;
entries.forEach(({ contentBoxSize, contentRect, target }) => {
if (target && target !== swiper.el) return;
newWidth = contentRect
? contentRect.width
: (contentBoxSize[0] || contentBoxSize).inlineSize;
newHeight = contentRect
? contentRect.height
: (contentBoxSize[0] || contentBoxSize).blockSize;
});
if (newWidth !== width || newHeight !== height) {
resizeHandler();
}
});
if (newWidth !== width || newHeight !== height) {
resizeHandler();
}
});
observer.observe(swiper.el);
};

const removeObserver = () => {
if (animationFrame) {
window.cancelAnimationFrame(animationFrame);
}
if (observer && observer.unobserve && swiper.el) {
observer.unobserve(swiper.el);
observer = null;
Expand Down

0 comments on commit 0567641

Please sign in to comment.