How to understand reflow and redraw?

Reflow and repaint are two key concepts in the browser rendering process.

1. Concept:

  • Reflow refers to the process by which the browser recalculates the position and size of elements when calculating the document flow layout (layout). Reflow is triggered when elements on the page change size, add or delete elements, or change text content. Reflow may cause the position and size of other elements to also need to be recalculated, which may be a relatively performance-intensive operation.
  • Redrawing refers to the process by which the browser draws updated element styles to the screen after reflow. Redrawing is triggered when an element's appearance properties (such as color, background, etc.) change. Redrawing does not involve layout calculations, so its performance is relatively less expensive than reflowing.

The specific browser parsing and rendering mechanism is as follows:

Insert image description here

  • Parse HTML, generate DOM tree, parse CSS, generate CSSOM tree

  • Combine the DOM tree and CSSOM tree to generate a render tree (Render Tree)

  • Layout (reflow): Perform reflow (Layout) based on the generated rendering tree to obtain the geometric information (position, size) of the node

  • Painting: Obtain the absolute pixels of the node based on the geometric information obtained from the rendering tree and reflow.

  • Display: Send pixels to the GPU and display them on the page

In the initial rendering stage of the page, reflow is inevitably triggered. It can be understood that the page starts with blank elements, and new elements are added later to change the page layout;

When our modifications to the DOM cause changes in the geometric dimensions of the DOM (such as modifying the width, height, or hiding elements, etc.), the browser needs to recalculate the geometric attributes of the element and then draw the calculated results ;

When our modification to the DOM results in a change of style (color or background-color), but does not affect its geometric properties, the browser does not need to recalculate the geometric properties of the element and directly draws a new style for the element. Here is Just triggering a repaint.

2. Example:

When it comes to reflow and redraw, here are some common examples:

  1. Modify the dimensions of an element : For example, dynamically modify the width or height of an element through JavaScript . This triggers a reflow because the browser needs to recalculate the layout of the element and subsequently redraw it.
// 触发回流和重绘
element.style.width = "200px";
element.style.height = "100px";
  1. Change font attributes : If you change the font size, font style and other attributes of an element in CSS , reflow and redrawing will be triggered. Because changes in the size of the text may cause the position and size of surrounding elements to change.
/* 触发回流和重绘 */
.element {
    
    
  font-size: 16px;
  font-weight: bold;
}
  1. Adding or removing elements : When elements are dynamically added or removed via JavaScript , reflow and redraw are triggered. Because the browser needs to recalculate the layout of the document flow and update the display.
// 触发回流和重绘
var newElement = document.createElement("div");
parentElement.appendChild(newElement);

// 触发回流和重绘
var elementToRemove = document.getElementById("elementId");
parentElement.removeChild(elementToRemove);
  1. Modify the position of an element : If you change the position of an element by modifying its positioning properties (such as top, left ), reflow and redrawing will be triggered. Because the layout of surrounding elements may be affected.
// 触发回流和重绘
element.style.position = "absolute";
element.style.top = "50px";
element.style.left = "100px";
  1. Change the background color or border style of an element : When the element's background color, border style and other appearance attributes are modified through CSS , a redraw will be triggered. This will not cause a reflow since changes to these properties will not affect the layout.
/* 触发重绘,不触发回流 */
.element {
    
    
  background-color: red;
  border: 1px solid black;
}

It's important to note that different browsers may handle reflow and redraw slightly differently. In addition, modern browsers often optimize frequent reflows to minimize performance overhead. However, excessive reflows and redraws may still cause page performance degradation, so you should try to avoid unnecessary operations when writing code.

3. Understanding the relationship between reflow and redrawing can be simply as follows:

  1. Reflow is inevitably accompanied by redrawing : when the position and size of an element change, not only reflow calculations are required, but also redrawing operations are required. So every reflow will cause a redraw.

  2. Redrawing does not necessarily cause reflow : when the appearance properties of an element change, it only needs to be redrawn without recalculating the layout, so it does not necessarily cause reflow. For example, changing the color, background and other style attributes of the element.

Since reflow involves layout calculation, it has a large performance overhead and will cause the page to be re-rendered, affecting user experience and page performance. Therefore, frequent reflow operations should be avoided during the development process. The following measures can be taken:

  • Batch modification of styles : Group the modifications of multiple styles together, and achieve batch changes of styles by adding or removing CSS classes to reduce the number of reflows.
  • Avoid forced layout synchronization : A typical example is when querying certain layout properties (such as offsetTop, offsetWidth, etc.), the browser will force a reflow to ensure that the latest value is obtained. If it cannot be avoided, try to reduce the number of such operations as much as possible.
  • Use transform instead of top/left : Using the transform attribute of CSS3 for displacement operations can avoid reflow and have better performance.

In short, understanding the principles of reflow and redrawing can help us optimize the code, reduce unnecessary performance overhead, and improve the rendering performance of the page.

4. The following are some advantages and disadvantages of methods to reduce reflow and redraw:

advantage:

  1. Improve page performance : Reducing reflows and redraws reduces the browser's calculation and rendering workload, thereby improving page performance and responsiveness.
  2. Reduce resource consumption : Reflow and redraw consume CPU and GPU resources. By reducing their frequency, you can reduce the usage of system resources and extend battery life.
  3. Improve user experience : Reducing reflow and redrawing can reduce page loading and rendering delays and improve the user's interaction experience with web pages.

shortcoming:

  1. Possible increase in code complexity : In order to reduce reflow and redrawing, the code may need to be modified and additional logic introduced, thereby increasing code complexity and maintenance costs.
  2. May affect development efficiency : While pursuing performance best practices, more time and energy may need to be invested in code optimization and testing.
  3. Not applicable in all cases : Sometimes, reflows and redraws may not be completely avoided in order to achieve a specific functionality or effect. In this case, there is a trade-off between performance and functionality.

In summary, reducing reflow and redrawing can effectively improve page performance and user experience, but it requires a trade-off between code complexity and development efficiency. In actual development, decisions need to be made based on specific circumstances and appropriate optimization methods selected.

5. How to reduce reflow and redrawing?

  1. Modify styles in batches : Try to avoid modifying the style of a single element multiple times. Instead, modify multiple styles at once by adding or removing CSS classes. This limits the number of reflows and redraws.
// 不推荐的方式(多次回流和重绘)
element.style.width = "200px";
element.style.height = "100px";

// 推荐的方式(一次回流和重绘)
element.classList.add("new-styles");
  1. Use transform instead of positioning attributes : When changing the position of an element, use the transform attribute instead of top/left attributes. Because the transform attribute will only trigger redrawing, not reflow.
// 不推荐的方式(触发回流和重绘)
element.style.position = "absolute";
element.style.top = "50px";
element.style.left = "100px";

// 推荐的方式(只触发重绘)
element.style.transform = "translate(100px, 50px)";
  1. Caching layout information : If you need to read the layout attributes (such as width, height) of an element multiple times, it is best to cache these attribute values ​​first to avoid triggering reflow repeatedly.
// 不推荐的方式(重复触发回流)
var width = element.offsetWidth;
console.log(width);
var height = element.offsetHeight;
console.log(height);

// 推荐的方式(缓存布局属性值)
var width = element.offsetWidth;
var height = element.offsetHeight;
console.log(width, height);
  1. Use separate DOM batch processing : If you need to modify the DOM multiple times , you can group these modification operations together before inserting them into the document. This reduces the number of reflows and redraws.
// 不推荐的方式(多次回流和重绘)
for (var i = 0; i < 100; i++) {
    
    
  var newElement = document.createElement("div");
  parentElement.appendChild(newElement);
}

// 推荐的方式(批量插入元素,减少回流和重绘)
var fragment = document.createDocumentFragment();
for (var i = 0; i < 100; i++) {
    
    
  var newElement = document.createElement("div");
  fragment.appendChild(newElement);
}
parentElement.appendChild(fragment);

By adopting the above methods, the number of reflows and redraws can be minimized, the performance and response speed of the page can be improved, and the page performance and user experience can be improved.

Guess you like

Origin blog.csdn.net/He_9a9/article/details/133295486