← 中文资源

简体中文版本

布局读写按帧分批避免重排

交替读写布局属性会触发同步重排:先把 getBoundingClientRect 批量读完,再批量写样式,让每帧只做一次布局计算,rAF 回调是天然的批次边界。

阅读英文原文

实现说明

布局读写按帧分批避免重排以函数 resizeCards、thrash为骨架。 循环只出现在 for (const card of cards),它的每次迭代处理一个元素。

使用要点

  • 浏览器才是这里的运行环境:document、requestAnimationFrame 在 Node 里拿不到。
  • 跑完文件,输出里会留下标记——resize scheduled for next frame:。

常见问题

「布局读写按帧分批避免重排」能在裸 Node.js 里跑吗?

不能——它用到 document、requestAnimationFrame。这些 API 只在浏览器里有效,裸 Node 进程没有这些能力,请放到页面(或 DevTools 控制台)里执行。

入口签名:function resizeCards(cards: HTMLElement[], scale: number)

核心语句

const widths = cards.map((card) => card.getBoundingClientRect().width);
requestAnimationFrame(() => resizeCards(cards, 0.8));
cards.forEach((card, index) => {
  card.style.width = `${Math.round(widths[index] * scale)}px`;
});

代码示例

// Alternating layout reads and writes forces synchronous reflow: batch all reads first, then all writes -
// requestAnimationFrame is the natural batch boundary
function resizeCards(cards: HTMLElement[], scale: number): void {
  // Read phase: grab every current width in one go, no writes in between
  const widths = cards.map((card) => card.getBoundingClientRect().width);

  // Write phase: apply the styles in bulk so the browser lays out once
  cards.forEach((card, index) => {
    card.style.width = `${Math.round(widths[index] * scale)}px`;
  });
}

const cards = Array.from(document.querySelectorAll<HTMLElement>('.card'));

// Every frame reads first, writes second; interleaving them in one callback doubles the reflow count
requestAnimationFrame(() => resizeCards(cards, 0.8));
console.log('resize scheduled for next frame:', cards.length, 'cards');

// Anti-pattern for contrast: read then write per element - n elements trigger n synchronous layouts
function thrash(cards: HTMLElement[], scale: number): void {
  for (const card of cards) {
    card.style.width = `${Math.round(card.getBoundingClientRect().width * scale)}px`;
  }
}