Home Web Front-end JS Tutorial Reflows and Repaints in Javascript

Reflows and Repaints in Javascript

Oct 18, 2024 pm 10:42 PM

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>
Copy after login
Copy after login

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:

  1. Recalculate the positions and dimensions of all elements affected by the change.
  2. 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.

Reflows and Repaints in Javascript

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>
Copy after login
Copy after login

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

  1. DOM Construction: The browser parses HTML to build the DOM (Document Object Model) tree.
  2. CSSOM Construction: CSS is parsed to build the CSSOM (CSS Object Model) tree.
  3. Render Tree Construction: The DOM and CSSOM are combined to create the render tree, which contains the visual information for each visible element.
  4. Layout (Reflow): The browser calculates the position and size of each visible element in the render tree.
  5. Paint: The browser fills in pixels based on the visual properties like colors, borders, shadows, etc.
  6. 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

  1. 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.

  2. 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 login
    Copy after login
  3. 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 login
    Copy after login
  4. Reduce complexity of CSS: Avoid deeply nested elements and overly complex CSS rules that can trigger reflows.

  5. 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

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...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

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.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

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 using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

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...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

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.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

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 Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

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.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

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. �...

See all articles