问题
What kinds of activities will trigger reflow of web page with DOM?
It seems there are different points of view. According to http://www.nczonline.net/blog/2009/02/03/speed-up-your-javascript-part-4/, it happens
- When you add or remove a DOM node.
- When you apply a style dynamically (such as element.style.width="10px").
- When you retrieve a measurement that must be calculated, such as accessing offsetWidth, clientHeight, or any computed CSS value (via getComputedStyle() in DOM-compliant browsers or currentStyle in IE).
However, according to http://dev.opera.com/articles/view/efficient-javascript/?page=3, taking measurement triggers reflow only when there is already reflow action queued.
Does anybody have any more ideas?
回答1:
Both articles are correct. One can safely assume that whenever you're doing something that could reasonably require the dimensions of elements in the DOM be calculated that you will trigger reflow.
In addition, as far as I can tell, both articles say the same thing.
The first article says reflow happens when:
When you retrieve a measurement that must be calculated, such as accessing offsetWidth, clientHeight, or any computed CSS value (via getComputedStyle() in DOM-compliant browsers or currentStyle in IE), while DOM changes are queued up to be made.
The second article states:
As stated earlier, the browser may cache several changes for you, and reflow only once when those changes have all been made. However, note that taking measurements of the element will force it to reflow, so that the measurements will be correct. The changes may or may not not be visibly repainted, but the reflow itself still has to happen behind the scenes.
This effect is created when measurements are taken using properties like offsetWidth, or using methods like getComputedStyle. Even if the numbers are not used, simply using either of these while the browser is still caching changes, will be enough to trigger the hidden reflow. If these measurements are taken repeatedly, you should consider taking them just once, and storing the result, which can then be used later.
I take this to mean the same thing they said earlier. Opera will try its hardest to cache values and avoid reflow for you, but you shouldn't rely on its ability to do so.
For all intents and purposes just believe what they both say when they say that all three types of interactions can cause reflow.
Cheers.
回答2:
Look at the "Rendering triggered by Property Read Access" section of Understanding Internet Explorer Rendering Behaviour, where the following code in IE will cause rendering activity.
function askforHeight () {
$("#lower").height();
}
回答3:
document.body.style.display = 'none';
document.body.style.display = 'block';
This often solves those incomprehensible layout bugs.
来源:https://stackoverflow.com/questions/510213/when-does-reflow-happen-in-a-dom-environment