Reflows and Repaints in Javascript
What are the best practices for optimizing CSS to reduce unnecessary reflows and repaints, especially in large-scale applications?
1. Reflow (Layout Recalculation):
A reflow (also called layout or re-layout) occurs when the browser recalculates the position, size, and layout of elements on the page. This process happens every time the layout of the page changes such as when elements are added, removed, resized, or their visibility changes. It’s a more complex and time-consuming operation
Example :
<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>
When does a reflow happen?
- Adding, removing, or modifying DOM elements (e.g., appendChild, removeChild).
- Changing the layout by adjusting CSS styles like width, height, margin, padding, etc.
- Resizing the window or changing the size of elements.
- Changing the font size or font properties.
- Using methods like offsetWidth, offsetHeight, scrollTop, getBoundingClientRect() because they force the browser to recalculate layout.
How reflow works:
When you change something that affects the layout of the page, the browser has to:
- Recalculate the positions and dimensions of all elements affected by the change.
- Rebuild the layout tree, which is the internal representation of how the elements are laid out.
If many elements are affected by a single change, the reflow can be costly and slow down the performance of your site.
2. Repaint (Visual Update)
A repaint (or redraw) occurs when visual properties of an element change but the layout doesn’t. It’s less expensive than a reflow because it only requires updating the appearance of elements without recalculating their position or layout. Repaints happen after the layout is recalculated (in cases where both are needed) or when non-layout-affecting properties are changed, like color or visibility.
Example :
<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>
When does a repaint happen?
- Changing the background-color, border-color, or visibility properties.
- Changing the box-shadow, outline, or color of an element.
- Updating opacity (opacity), transforms (transform), or z-index.
A repaint doesn’t involve recalculating layout, so it’s faster than reflow, but it still requires redrawing parts of the page, which takes some time.
The Rendering Pipeline
- DOM Construction: The browser parses HTML to build the DOM (Document Object Model) tree.
- CSSOM Construction: CSS is parsed to build the CSSOM (CSS Object Model) tree.
- Render Tree Construction: The DOM and CSSOM are combined to create the render tree, which contains the visual information for each visible element.
- Layout (Reflow): The browser calculates the position and size of each visible element in the render tree.
- Paint: The browser fills in pixels based on the visual properties like colors, borders, shadows, etc.
- Composite: The browser composes the different painted layers (for complex elements like animations, 3D transforms, etc.) and displays them on the screen.
Performance Impact
- Reflow: Expensive in terms of performance, especially if it affects large parts of the page or is triggered repeatedly (e.g., in a loop or on resize). It affects the layout of the page and requires recalculating positions and sizes of elements.
- Repaint: Less expensive than a reflow but still impacts performance, especially if many elements need to be repainted frequently.
How to Optimize Reflows and Repaints
Minimize DOM manipulation : Use techniques like batching DOM updates (as mentioned earlier) or DocumentFragment to make multiple changes at once, instead of one by one.
-
Avoid layout thrashing : If you read a layout property (e.g., offsetHeight) and immediately write (change the layout) in the same cycle, it forces a reflow, known as layout thrashing. To avoid this, separate reading and writing DOM properties in different steps.
<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>
Copy after loginCopy after login -
Use CSS classes : Instead of modifying individual styles, use CSS classes to make changes. The browser handles class switching more efficiently.
<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>
Copy after loginCopy after login Reduce complexity of CSS: Avoid deeply nested elements and overly complex CSS rules that can trigger reflows.
Use visibility: hidden instead of display: none when you just want to hide an element without affecting layout. display: none triggers a reflow, while visibility: hidden only triggers a repaint.
Conclusion
- Reflows involve recalculating the layout of the page and are more costly in terms of performance.
- Repaints update the visual appearance without affecting layout and are less costly.
- Minimizing both helps keep your site responsive and fast, improving user experience.
The above is the detailed content of Reflows and Repaints in Javascript. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...
