By Paul Irish
Quoting two code snippets from above link to show the differences.
Code snippet 1 (layout twice):
1234 elementA.className = "a-style";var heightA = elementA.offsetHeight; // layout is neededelementB.className = "b-style"; // invalidates the layoutvar heightB = elementB.offsetHeight; // layout is needed again
Code snippet 2 (layout only once):
1234 elementA.className = "a-style";elementB.className = "b-style";var heightA = elementA.offsetHeight; // layout is needed and calculatedvar heightB = elementB.offsetHeight; // layout is up-to-date (no work)
elem.scrollTopalso, setting them
elem.focus()can trigger a double forced layout (source)
window.getComputedStyle() will typically force style recalc (source)
window.getComputedStyle() will force layout, as well, if any of the following is true:
- The element is in a shadow tree
- There are media queries (viewport-related ones). Specifically, one of the following: (source)
- The property requested is one of the following: (source)
-left, or shorthand] only if the margin is fixed.
-left, or shorthand] only if the padding is fixed.
window.getMatchedCSSRules()only forces style
doc.scrollingElementonly forces style
- Quite a lot; haven’t made an exhaustive list , but Tony Gentilcore’s 2011 Layout Triggering List pointed to a few.
- Lots & lots of stuff, …including copying an image to clipboard (source)
- If layout is forced, style must be recalculated first. So forced layout triggers both operations. Their costs are very dependent on the content/situation, but typically both operations are similar in cost.
- The above data was built by reading the Blink source, so it’s true for Chrome, Opera, and most android browsers.
- Tony Gentilcore’s Layout Triggering List was for 2011 WebKit and generally aligns with the above.
- Modern WebKit’s instances of forced layout are mostly consistent:
updateLayoutIgnorePendingStylesheets– GitHub search – WebKit/WebKit
- Gecko’s reflow appears to be requested via FrameNeedsReflow. Results:
FrameNeedsReflow– mozilla-central search
- No concrete data on Edge/IE, but it should fall roughly in line, as the return values for these properties are spec’d. What would differ is the amount of clever optimization.
- forced layout (and style recalc):
updateLayoutIgnorePendingStylesheets– Chromium Code Search
- forced style recalc:
updateLayoutTree– Chromium Code Search
- Avoiding layout thrashing — Web Fundamentals
- Fixing Layout thrashing in the real world | Matt Andrews
- Timeline demo: Diagnosing forced synchronous layouts – Google Chrome
- Preventing ‘layout thrashing’ | Wilson Page
- Rendering: repaint, reflow/relayout, restyle / Stoyan
- We spent a week making Trello boards load extremely fast. Here’s how we did it. – Fog Creek Blog
- Minimizing browser reflow | PageSpeed Insights | Google Developers