ResizeObserver loop completed with undelivered notifications. 報錯
js 使用 ResizeObserver 時報錯,代碼實現邏輯如下:
function observeVideoDom (width: number, height: number) { const videoDom = document.getElementById('videoDom') if (!videoDom) return if (window.ResizeObserver) { // ResizeObserver 在 iOS13.4及以上,安卓 4.4.5及以上才支持,如果不支持用輪詢判斷 const resizeObserver = new ResizeObserver(() => { videoSizeReset(width, height) }) resizeObserver.observe(videoDom) } else { let previousWidth = videoDom.clientWidth let previousHeight = videoDom.clientHeight const checkSize = () => { const currentWidth = videoDom.clientWidth const currentHeight = videoDom.clientHeight if (currentWidth !== previousWidth || currentHeight !== previousHeight) { videoSizeReset(width, height) previousWidth = currentWidth previousHeight = currentHeight } } const scheduleCheck = () => { checkSize() requestAnimationFrame(scheduleCheck) } requestAnimationFrame(scheduleCheck) } }
主要功能是監測 videoDom 元素的盒子大小變化后,重新賦值videoDom 元素的盒子大小,由于重新賦值的操作會再次改變 videoDom 元素的盒子大小,會導致報錯了 ResizeObserver loop completed with undelivered notifications.
解決方案,給 ResizeObserver 的回調函數加 防抖或者 requestAnimationFrame
改后如下:
function observeVideoNativeDom (width: number, height: number) { const videoNativeDom = document.getElementById('video-native') if (!videoNativeDom) return if (window.ResizeObserver) { // ResizeObserver 在 iOS13.4及以上,安卓 4.4.5及以上才支持,如果不支持用輪詢判斷 const resizeObserver = new ResizeObserver(debounce(() => { videoSizeReset(width, height) }, 300)) resizeObserver.observe(videoNativeDom) } else { let previousWidth = videoNativeDom.clientWidth let previousHeight = videoNativeDom.clientHeight const checkSize = () => { const currentWidth = videoNativeDom.clientWidth const currentHeight = videoNativeDom.clientHeight if (currentWidth !== previousWidth || currentHeight !== previousHeight) { videoSizeReset(width, height) previousWidth = currentWidth previousHeight = currentHeight } } const scheduleCheck = () => { checkSize() requestAnimationFrame(scheduleCheck) } requestAnimationFrame(scheduleCheck) } } // 或者
debounce 函數自己寫或者引入工具庫

浙公網安備 33010602011771號