🔍 inp.works

強制同期レイアウト:DOM書き込み後にジオメトリを読む

何が起きているか

通常レイアウトはJavaScriptが終わった後、フレームごとに1回行われます。しかしDOMを変更して直後にレイアウトプロパティ — offsetWidth、scrollHeight、getBoundingClientRect()、getComputedStyle() — を読むと、答えがあなたの未反映の変更に依存するため、ブラウザはその場で、同期的に、タスク内でレイアウトを計算せざるを得ません。

強制レイアウトは小さなページでは安価です。大きなDOMや、ループで繰り返す(レイアウトスラッシングになる)と、ハンドラーに数百msを追加します。

見分け方

直し方

問題

grid.style.width = next + "px"            // write: layout is now dirty
const rect = cell.getBoundingClientRect()  // read → forced synchronous layout

修正

const rect = cell.getBoundingClientRect()  // read first, layout is clean
grid.style.width = next + "px"             // write after; browser lays out
                                           // once, before the next paint
サイトを無料でスキャン →
Advertise here