Introduction
Reflow and repaint are two important concepts in the browser rendering process. Understanding them can help us optimize the performance of our web pages.
Reflow
Reflow is the process of recalculating the position and size of all elements in the DOM tree. When the layout of the page changes, the browser needs to reflow the page to recalculate the position and size of all elements. The following changes can trigger a reflow:
- Resizing the window
- Changing the width or height of an element
- Changing the padding, margin, or border of an element
- Changing the font size of an element
- Changing the position of an element
Repaint
Repaint is the process of updating the pixels on the screen. When the layout of the page changes, the browser needs to repaint the affected elements to update the pixels on the screen. The following changes can trigger a repaint:
- Changing the background color of an element
- Changing the text color of an element
- Changing the visibility of an element
- Changing the opacity of an element
- Changing the z-index of an element
How Browser render pages
The browser rendering process consists of several steps:
- Parse HTML: The browser parses the HTML code and creates a DOM tree.
- Parse CSS: The browser parses the CSS code and creates a CSSOM tree.
- Combine DOM and CSSOM: The browser combines the DOM tree and CSSOM tree to create a render tree.
- Layout: The browser calculates the position and size of all elements in the render tree.
- Paint: The browser paints the pixels on the screen based on the render tree.
- Composite: The browser combines the painted pixels to create the final image on the screen.
- In the process of rendering a web page, the browser may need to trigger reflows and repaints to update the layout and appearance of the page.
- Reflow: Recalculating the position and size of all elements in the DOM tree.
- Repaint: Updating the pixels on the screen.
- Reflow will trigger repaint, but repaint does not necessarily trigger reflow.