前端性能踩坑:requestAnimationFrame里读offsetHeight触发强制同步布局

[复制链接]
发表于 3 天前 | 显示全部楼层 |阅读模式
现象:一个下拉列表滚动时掉帧,Performance 面板里紫色 Layout 块密密麻麻,单帧耗时 30ms+。代码逻辑很简单:滚动时用 rAF 更新指示条位置。
  1. function onScroll() {
  2.   requestAnimationFrame(() => {
  3.     const top = list.offsetHeight;      // 读几何
  4.     indicator.style.height = top + 'px'; // 写样式
  5.   });
  6. }
  7. window.addEventListener('scroll', onScroll, { passive: true });
复制代码

以为是 rAF 就万事大吉,结果每帧都在触发强制同步布局(forced reflow):rAF 回调执行在样式计算之前,此时读 offsetHeight 会让浏览器立刻把上一步的写操作 flush 掉,读写交替就是一帧一次 Layout。

排查:Chrome DevTools 的 Performance 录制里勾选 "Enable advanced paint instrumentation",看 Layout 的 Call Stack,栈顶就是那行 offsetHeight。命令行也可以用
  1. performance.measure
复制代码
打点确认。

修复:读写分离,缓存尺寸,只在 resize 时重新测量。
  1. let cachedH = 0;
  2. new ResizeObserver(entries => {
  3.   cachedH = entries[0].contentRect.height;
  4. }).observe(list);
  5. function onScroll() {
  6.   requestAnimationFrame(() => {
  7.     indicator.style.height = cachedH + 'px'; // 只写不读
  8.   });
  9. }
复制代码

改完单帧降到 4ms 左右,Layout 块只剩 resize 时的几次。

结论:rAF 不等于不会触发同步布局,它只保证回调时机,不保证读写顺序。凡是在同一帧里先 getBoundingClientRect/offsetHeight 再改 style,都会被打回同步布局。更隐蔽的是 ResizeObserver 回调里读写也会触发循环警告,测和写要拆到不同回调里。另一个坑:display:none 的元素读 offsetHeight 恒为 0,缓存前记得确认元素在文档流里。
发表于 3 天前 | 显示全部楼层
问题类型:浏览器渲染性能 / 强制同步布局(forced reflow),不是插件加载或 manifest 问题。

排查步骤:
1. 在 rAF 回调里把读写彻底分开:先读所有几何(offsetHeight、getBoundingClientRect),缓存到变量,再统一写 style。示例:
  1. let h = 0;
  2. function onScroll() {
  3.   requestAnimationFrame(() => {
  4.     if (!h) h = list.offsetHeight; // 只读一次并缓存
  5.     indicator.style.height = h + 'px';
  6.   });
  7. }
复制代码
2. 若高度会变,用 ResizeObserver 监听 list,在回调里更新缓存值,滚动路径只读缓存。
3. 指示条位置优先用 transform: translateY() 代替改 height,避免触发布局。
4. Performance 面板勾选 “Enable advanced paint instrumentation”,看 Layout 是否仍出现在 rAF 帧内;配合 “Layout Shift” 轨道确认来源。

需要确认:Chrome 版本、list 是否在滚动中改变尺寸、indicator 是否 absolute 定位。给个最小复现(CodePen)可进一步定位。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

在本版发帖
关注公众号
QQ客服返回顶部