重排(也称为布局或重新布局)。每当页面布局发生变化时,例如添加、删除、调整大小或其可见性发生变化时,都会发生此过程。这是一个比较复杂和耗时的操作
例子 :<div id="box" style="width: 100px; height: 100px; background-color: blue;"></div> <script> const box = document.getelementbyid('box'); // triggering a reflow by changing width and height box.style.width = '200px'; box.style.height = '200px'; // triggering a repaint by changing the background color box.style.backgroundcolor = 'red'; </script>
repaint (或 redraw)。它比回流便宜,因为它只需要更新元素的外观,而无需重新计算其位置或布局。重新绘制在重新计算布局后(在需要两者的情况下)或在更改不影响布局的属性(例如颜色或可见性)时发生。
例子 :<div id="box" style="width: 100px; height: 100px; background-color: blue;"></div> <script> // triggering a repaint by changing the background color box.style.backgroundcolor = 'red'; </script>
渲染管线
最小化 dom 操作 :使用 批量 dom 更新(如前所述)或 documentfragment 等技术一次性进行多项更改,而不是一一。
避免布局抖动:如果您读取布局属性(例如,offsetheight)并立即在同一周期内写入(更改布局),则会强制回流,称为布局抖动。为了避免这种情况,请在不同的步骤中分开读取和写入 dom 属性。
const height = element.offsetheight; element.style.height = height + 'px';
使用 css 类 :不要修改单个样式,而是使用 css 类进行更改。浏览器更有效地处理类切换。
element.classList.add('newClass');
降低 css 的复杂性:避免深层嵌套的元素和过于复杂的 css 规则,从而触发回流。
当您只想隐藏元素而不影响布局时,请使用visibility:hidden而不是display:none。 display: none 会触发重排,而visibility: hide 只会触发重绘。
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号