2026-01-20 16:19:16 +08:00
---
title: Batch DOM CSS Changes
impact: MEDIUM
impactDescription: reduces reflows/repaints
tags: javascript, dom, css, performance, reflow
---
## Batch DOM CSS Changes
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.
**Incorrect (interleaved reads and writes force reflows): **
``` typescript
function updateElementStyles ( element : HTMLElement ) {
2026-02-05 21:40:43 +08:00
element . style . width = '100px' ;
const width = element . offsetWidth ; // Forces reflow
element . style . height = '200px' ;
const height = element . offsetHeight ; // Forces another reflow
2026-01-20 16:19:16 +08:00
}
```
**Correct (batch writes, then read once): **
``` typescript
function updateElementStyles ( element : HTMLElement ) {
// Batch all writes together
2026-02-05 21:40:43 +08:00
element . style . width = '100px' ;
element . style . height = '200px' ;
element . style . backgroundColor = 'blue' ;
element . style . border = '1px solid black' ;
2026-01-20 16:19:16 +08:00
// Read after all writes are done (single reflow)
2026-02-05 21:40:43 +08:00
const { width , height } = element . getBoundingClientRect ( ) ;
2026-01-20 16:19:16 +08:00
}
```
**Better: use CSS classes **
``` css
. highlighted-box {
width : 100 px ;
height : 200 px ;
background-color : blue ;
border : 1 px solid black ;
}
```
``` typescript
function updateElementStyles ( element : HTMLElement ) {
2026-02-05 21:40:43 +08:00
element . classList . add ( 'highlighted-box' ) ;
2026-01-20 16:19:16 +08:00
2026-02-05 21:40:43 +08:00
const { width , height } = element . getBoundingClientRect ( ) ;
2026-01-20 16:19:16 +08:00
}
```
2026-02-05 21:40:43 +08:00
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.