Skip to content Skip to sidebar Skip to footer

Alternatives To Re-flow And Re-paint

I've read on SO and elsewhere that re-paints and re-flows are expensive for the browser to perform. I'm curious about CSS/JS alternatives to re-paint/display:none and re-flow/visi

Solution 1:

I think you misinterpret that statement.

If you're dynamically generating elements, consider these two scenerios:

  1. Generate an element, add it to the DOM. Repeat.
  2. Create a DOMDocumentFragment first. Add the elements to the fragment. Repeat. Add the fragment to the DOM.

Method 1 will do a re-paint for each element you add. Method 2 will only do one repaint at the end. If you have a low number of elements to add method 1 is probably fine. If you're adding many nodes method 2 will be considerably faster.

This is what is meant by re-paints are expensive.


Maybe this is a good way of looking at it:

A re-paint has a base cost of say 100. Creating a DOM element and appending it costs 1. If you're doing method 1 for 7 elements your cost will be (1 + 100) * 7 = 707. If you're doing method 2 your cost will be: 1 * 7 + 100 = 107. Which is considerably lower. The numbers are just for illustration. There is probably a lot more to it than this, but I think this is a good and simple way of looking at re-paint performance.


Solution 2:

There is no simple formula. To begin with, every browser has its own way to deal with reflows and repaints. Usually, browsers will try to postpone reflows as much as possible, since they can be very expensive, as you know.

In general, keep in mind that the following operations always trigger a reflow:

  • Changing the DOM tree by appending, removing or moving nodes.
  • Changing CSS calculated properties such as offsetWidth
  • Reading computed CSS values with getComputedStyle (or currentStyle on old IE)

(See When does reflow happen in a DOM environment?.)

Setting styles will usually cause a reflow, but browsers will try to avoid it if the change can't affect other elements' positions or dimensions.

For some fun with reflows, see Will it reflow?


Post a Comment for "Alternatives To Re-flow And Re-paint"