Understanding Reflow and Repaint in the browser
Tags: html, css, webdev, beginners
Published: 2020-09-27 16:40:02

Recently I came to know about **Reflow and Repaint**. How it's affecting web performance. I am writing this post to give insights about reflow and repaint.
Before Jumping into the topic, let's understand how the browser renders the website.

![How browser render the website](https://dev-to-uploads.s3.amazonaws.com/i/vbtr2gfaitr0am5nl4io.png)

* When the user enters the URL, It will fetch the HTML source code from the server
* Browser Parse the HTML source code and convert into the Tokens `<, TagName, Attribute, AttributeValue, >`
* The Tokens will convert into the nodes and will construct the **DOM Tree**
* The **CSSOM Tree** will generate from the CSS rules
* The DOM and CSSOM tree will combine into the **RenderTree**
* The RenderTree are constructed as below:
  * Start from the root of the dom tree and compute which elements are visible and their computed styles
  * RenderTree will ignore the not visible elements like `(meta, script, link)` and `display:none`
  * It will match the visible node to the appropriate CSSOM rules and apply them
* **Reflow:** Calculate the position and size of each visible node
* **Repaint:** now, the browser will paint the renderTree on the screen

# Repaint and Reflow

* The Repaint occurs when changes are made to the appearance of the elements that change the visibility, but doesn't affect the layout
  * Eg: Visibility, background color, outline
* Reflow means re-calculating the positions and geometries of elements in the document. The Reflow happens when changes are made to the elements, that affect the layout of the partial or whole page. The Reflow of the element will cause the subsequent reflow of all the child and ancestor elements in the DOM

Both Reflow and Repaints are an expensive operation

According to Opera, most reflows essentially cause the page to be re-rendered:
> Reflows are very expensive in terms of performance, and is one of the main causes of slow DOM scripts, especially on devices with low 
> processing power, such as phones. In many cases, they are equivalent to laying out the entire page again.

Here is the video of reflow visualization.

{% youtube dndeRnzkJDU %}

# What Causes the Reflows and Repaints
* Reflow will happen when Adding, Removing, Updating the DOM nodes
* Hiding DOM Element with `display: none` will cause both reflow and repaint
* Hiding DOM Element with `visibility: hidden` will cause the only repaint, because no layout or position change
* Moving, animating a DOM node will trigger reflow and repaint
* Resizing the window will trigger reflow
* Changing font-style alters the geometry of the element. That means that it may affect the position or size of other elements on the page, both of which require the browser to perform reflow.
Once those layout operations have completed any damaged pixels will need to be a repaint
* Adding or removing Stylesheet will cause the reflow/repaint
* Script manipulating the DOM is the expensive operation because they have recalculated each time the document, or part of the document modified. As we have seen from all the many things that trigger a reflow, it can occur thousands and thousands of times per second

```javascript
var bodyStyle = document.body.style; // cache
 
bodyStyle.padding = "20px"; // reflow, repaint
bodyStyle.border = "10px solid red"; // reflow, repaint
 
bodyStyle.color = "blue"; // repaint only, no dimensions changed
bstyle.backgroundColor = "#cc0000"; // repaint
 
bodyStyle.fontSize = "2em"; // reflow, repaint
 
// new DOM element - reflow, repaint
document.body.appendChild(document.createTextNode('Hello!'));
```

# Minimizing repaints and reflows
The strategy to reduce the negative effects of **reflows/repaints** on the user experience is to simply have fewer reflows and repaints and fewer requests for style information, so the browser can optimize reflows. How to go about that?

* Don't change individual styles, one by one. Best for sanity and maintainability is to change the class names, not the styles. 
If the styles are dynamic, edit the **cssText** property

```javascript
// bad
var left = 10,
    top = 10;
el.style.left = left + "px";
el.style.top  = top  + "px";
 
// better 
el.className += " theclassname";
 
// or when top and left are calculated dynamically...
 
// better
el.style.cssText += "; left: " + left + "px; top: " + top + "px;";
```

* Batch DOM Changes
  * Use a `documentFragment` to hold temp changes
  * Clone, update, replace the node
  * Hide the element with `display: none` (1 reflow, 1 repaint), add 100 changes, restore the display (total 2 reflow, 2 repaint)

* Don't ask for computed styles repeatedly, cache them into the variable
  * Multiple reads/writes (like for the height property of an element)
    * Writes, then reads, from the DOM, multiple times causing document reflows
    * Read(cached), write(invalidate layout), read(trigger layout).
    * To fix: read everything first then write everything

# Chrome Tool Performance
Chrome provides a great tool that helps us to figure out what is going on with our code, how many reflows (layout) and repaint do we have, and more details about the memory, events, etc.

## Bad code

```javascript
var box1Height = document.getElementById('box1').clientHeight;
document.getElementById('box1').style.height = box1Height + 10 + 'px';

var box2Height = document.getElementById('box2').clientHeight;
document.getElementById('box2').style.height = box2Height + 10 + 'px';

var box3Height = document.getElementById('box3').clientHeight;
document.getElementById('box3').style.height = box3Height + 10 + 'px';

var box4Height = document.getElementById('box4').clientHeight;
document.getElementById('box4').style.height = box4Height + 10 + 'px';

var box5Height = document.getElementById('box5').clientHeight;
document.getElementById('box5').style.height = box5Height + 10 + 'px';

var box6Height = document.getElementById('box6').clientHeight;
document.getElementById('box6').style.height = box6Height + 10 + 'px';
```

![performance monitor for bad code](https://dev-to-uploads.s3.amazonaws.com/i/jmxjpjztcjgi7zed4zxo.PNG)

## Optimized Code

```javascript
var box1Height = document.getElementById('box1').clientHeight;
var box2Height = document.getElementById('box2').clientHeight;
var box3Height = document.getElementById('box3').clientHeight;
var box4Height = document.getElementById('box4').clientHeight;
var box5Height = document.getElementById('box5').clientHeight;
var box6Height = document.getElementById('box6').clientHeight;

document.getElementById('box1').style.height = box1Height + 10 + 'px';
document.getElementById('box2').style.height = box2Height + 10 + 'px';
document.getElementById('box3').style.height = box3Height + 10 + 'px';
document.getElementById('box4').style.height = box4Height + 10 + 'px';
document.getElementById('box5').style.height = box5Height + 10 + 'px';
document.getElementById('box6').style.height = box6Height + 10 + 'px';
```

![performance monitor for optimized code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/893j3760gd989u2qd9e2.PNG)

# Resource:
* https://gist.github.com/faressoft/36cdd64faae21ed22948b458e6bf04d5
* https://www.phpied.com/rendering-repaint-reflowrelayout-restyle/
* http://www.stubbornella.org/content/2009/03/27/reflows-repaints-css-performance-making-your-javascript-slow/
* [CSSTriggers](https://csstriggers.com/)
* [What forces layout / reflow](https://gist.github.com/paulirish/5d52fb081b3570c81e3a)