返回 AiToEarn
js-batch-dom-css.md
1 ---
2 title: Avoid Layout Thrashing
3 impact: MEDIUM
4 impactDescription: prevents forced synchronous layouts and reduces performance bottlenecks
5 tags: javascript, dom, css, performance, reflow, layout-thrashing
6 ---
7
8 ## Avoid Layout Thrashing
9
10 Avoid interleaving style writes with layout reads. When you read a layout property (like `offsetWidth`, `getBoundingClientRect()`, or `getComputedStyle()`) between style changes, the browser is forced to trigger a synchronous reflow.
11
12 **This is OK (browser batches style changes):**
13 ```typescript
14 function updateElementStyles(element: HTMLElement) {
15 // Each line invalidates style, but browser batches the recalculation
16 element.style.width = '100px'
17 element.style.height = '200px'
18 element.style.backgroundColor = 'blue'
19 element.style.border = '1px solid black'
20 }
21 ```
22
23 **Incorrect (interleaved reads and writes force reflows):**
24 ```typescript
25 function layoutThrashing(element: HTMLElement) {
26 element.style.width = '100px'
27 const width = element.offsetWidth // Forces reflow
28 element.style.height = '200px'
29 const height = element.offsetHeight // Forces another reflow
30 }
31 ```
32
33 **Correct (batch writes, then read once):**
34 ```typescript
35 function updateElementStyles(element: HTMLElement) {
36 // Batch all writes together
37 element.style.width = '100px'
38 element.style.height = '200px'
39 element.style.backgroundColor = 'blue'
40 element.style.border = '1px solid black'
41
42 // Read after all writes are done (single reflow)
43 const { width, height } = element.getBoundingClientRect()
44 }
45 ```
46
47 **Correct (batch reads, then writes):**
48 ```typescript
49 function avoidThrashing(element: HTMLElement) {
50 // Read phase - all layout queries first
51 const rect1 = element.getBoundingClientRect()
52 const offsetWidth = element.offsetWidth
53 const offsetHeight = element.offsetHeight
54
55 // Write phase - all style changes after
56 element.style.width = '100px'
57 element.style.height = '200px'
58 }
59 ```
60
61 **Better: use CSS classes**
62 ```css
63 .highlighted-box {
64 width: 100px;
65 height: 200px;
66 background-color: blue;
67 border: 1px solid black;
68 }
69 ```
70 ```typescript
71 function updateElementStyles(element: HTMLElement) {
72 element.classList.add('highlighted-box')
73
74 const { width, height } = element.getBoundingClientRect()
75 }
76 ```
77
78 **React example:**
79 ```tsx
80 // Incorrect: interleaving style changes with layout queries
81 function Box({ isHighlighted }: { isHighlighted: boolean }) {
82 const ref = useRef<HTMLDivElement>(null)
83
84 useEffect(() => {
85 if (ref.current && isHighlighted) {
86 ref.current.style.width = '100px'
87 const width = ref.current.offsetWidth // Forces layout
88 ref.current.style.height = '200px'
89 }
90 }, [isHighlighted])
91
92 return <div ref={ref}>Content</div>
93 }
94
95 // Correct: toggle class
96 function Box({ isHighlighted }: { isHighlighted: boolean }) {
97 return (
98 <div className={isHighlighted ? 'highlighted-box' : ''}>
99 Content
100 </div>
101 )
102 }
103 ```
104
105 Prefer CSS classes over inline styles when possible. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain.
106
107 See [this gist](https://gist.github.com/paulirish/5d52fb081b3570c81e3a) and [CSS Triggers](https://csstriggers.com/) for more information on layout-forcing operations.
108
108 lines MARKDOWN