DEV Community

Cover image for Understanding Reflow and Repaint in the browser
Gopalakrishnan
Gopalakrishnan

Posted on • Updated on

Understanding Reflow and Repaint in the browser

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

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

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
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!'));
Enter fullscreen mode Exit fullscreen mode

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
// 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;";
Enter fullscreen mode Exit fullscreen mode
  • 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

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';
Enter fullscreen mode Exit fullscreen mode

performance monitor for bad code

Optimized Code

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';
Enter fullscreen mode Exit fullscreen mode

performance monitor for optimized code

Resource:

Top comments (9)

Collapse
 
hongquan09dth5 profile image
hongquan09dth5

Hello!, Could I have a question? Does the browser reflow for whole page even I only remove or add a node at somewhere on DOM tree or does the browser only reflow or repaint at the particular manipulated DOM?

Collapse
 
derick1530 profile image
Derick Zihalirwa

Yes It does recalculate the entire page.

Collapse
 
monaye profile image
Monaye Win

depends. if the parent node is within the document flow (not position absolute) then, yes, it has to reflow.

Collapse
 
avivhdr profile image
Aviv Hadar

I was just asked about this issue in a job interview.

Great Article but I am missing an example.
will this action result in a repaint of the entire page:
document.getElementById("demo").innerHTML = "Paragraph changed!";
?

And both repaint and reflow equally expensive?

Collapse
 
wangkangping profile image
wangkangping

Each time you try to update innerHTML, reflow will happen. Since updating innerHTML will cause the change of position of other elements. So that's why reflow happens.

In my view, reflow is more expensive than repaint. If you see how browser works, You will know it.
Here is the link: blog.sessionstack.com/how-javascri...

Collapse
 
moina profile image
Moin-A

Does it goes to say that even if we do as little as scroll the page when there is not literal css change, it cause the browser to repaint the page but does not cause the reflow

Collapse
 
santhoshmp89 profile image
Santhosh Kumar

Hi, Can you explain how does optimized code ran 2 layout where as bad code ran 7 layout, I am assuming that optimized code did batch update, If so please explain little bit.

Collapse
 
a90120411 profile image
Komodo

Batch DOM changes can reduce the reflow operation.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.