问题
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/visibility:hidden
that aren't as computationally demanding for the browser.
Just to be clear, and please correct me if I'm wrong, a common re-flow scenario is when you set display:none
on element that you want to toggle the display of, e.g., a dropdown menu. The re-flow means that the browser first "flows", i.e., displays, the element and everything beneath as visible content but then has to re-flow all of it because the dropdown menu needs to be hidden.
Commentary on whether the performance hit of re-flow and re-paint is actually something that people need to care about is welcome too.
回答1:
I think you misinterpret that statement.
If you're dynamically generating elements, consider these two scenerios:
- Generate an element, add it to the DOM. Repeat.
- 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.
回答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
(orcurrentStyle
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[citation needed].
For some fun with reflows, see Will it reflow?
来源:https://stackoverflow.com/questions/15205725/alternatives-to-re-flow-and-re-paint