Skip to content Skip to sidebar Skip to footer

Why Does Reading Dom Measurements Trigger A Layout/reflow?

I often read that changing a style after reading the element's style is a bad practice as it triggers an unnecessary reflow. Consider this code from here: Bad Code: elementA.classN

Solution 1:

Here we are simply reading already applied changes...

Not really. Assigning to className means the browser has to reflow, but it doesn't mean it already has reflowed when you're done assigning. It may wait (in modern browsers, will wait) until its next paint, which won't happen until after the current JavaScript code completes (at least).

But when you read a calculated property like clientHeight, the browser has to pause the JavaScript code and reflow the page so it can return an accurate number. So your "good" code does this:

elementA.className = "a-style";        // marks the layout stale
elementB.className = "b-style";        // marks the layout stale (no change)var heightA = elementA.offsetHeight;   // triggers reflowvar heightB = elementB.offsetHeight;   // no need for reflow, the layout isn't stale

Post a Comment for "Why Does Reading Dom Measurements Trigger A Layout/reflow?"