javascriptdombrowserrepaintreflow

Does Element.setAttribute trigger reflow?


I started learning about the inner working of browsers and came across reflow / repaint mechanism (and how it applies to React, but I don't want to digress).

In general, I think anything that makes browsers compute values/ visible changes will trigger reflow/ repaint.

However, I can't wrap my head around Element.setAttribute. Does it trigger reflow/ repaint in Chrome? What is the most efficient way to update multiple element attributes in dom tree?


Solution

  • However, I can't wrap my head around Element.setAttribute. Does it trigger reflow/ repaint in Chrome?

    setAttribute has no direct relationship to repaint/reflow. It depends on what attribute you set and what kind of element you set it. If you change the value of a checkbox, no repaint or reflow will occur, but if you change the value of a <input type="button">, then a repaint and reflow will occur.

    What is the most efficient way to update multiple element attributes in dom tree?

    "Most efficient" is hard to answer because each browser can be optimized to carry out tasks at different paces. But, generally speaking, you can follow these guidelines:

    1. Never update the DOM from within a loop as each iteration of the loop can cause a repaint/reflow.

      • Instead, you can build up a string of HTML and, when the loop is
        complete, inject the string one time and get all the updates.
      • You can also create and work with elements that have not been added to the DOM tree yet and exist only in memory. Then, you can place those elements in a single container that, itself, is not part of the DOM yet. Finally, you can add the container to the DOM and take the repaint/reflow hit just once.
    2. If you are doing many CSS manipulations, and are experiencing performance issues, you may want to look at the will-change CSS property, which can improve performance.

    There are many resources available to learn how to reduce the performance hits: