Page Speed Optimization

Batch DOM reads before style writes without breaking layout

Trace forced layout and restructure measurement dependencies without changing the interface.

Two rows of small document cards show alternating circular and square markers above grouped circles followed by grouped squares, with a browser outline beside them.

A page can download quickly and still hesitate when a menu opens or a filter changes. When JavaScript repeatedly changes geometry and immediately asks the browser to measure it, the interaction can spend time recalculating layout instead of showing the result.

Prove that layout is the bottleneck

Start with one reproducible interaction, such as expanding a comparison panel. Record the initial state, viewport, content count and exact action. A trace of opening an empty panel is not a useful baseline for a slow panel containing many rows. Keep these inputs stable while investigating, and include the version of the application in your notes.

Record the action in the browser's performance tools. In Chrome DevTools, select the interaction interval and inspect the Main track, then the Call tree and Bottom-up views. Layout work nested within a JavaScript task deserves attention. Repeated layout events around the same helper suggest a different problem from one necessary layout after all content has changed.

Use the Forced reflow insight, when available, to locate the measurement that demanded fresh geometry. Treat the reported function as a starting point. The earlier write that invalidated geometry may be in a different component, a framework callback or a third-party widget. Removing the read without understanding its purpose can leave a tooltip or selection indicator in the wrong place.

If the delay occurs before the first useful screen, investigate render-blocking resources separately. This guide concerns unnecessary measurement cycles during updates. It does not claim that every slow interaction is a layout problem or that eliminating a warning guarantees a particular field result.

Separate invalidation from measurement

Changing content or geometry can make the browser's previous layout information outdated. A subsequent geometry read may require it to calculate current positions and sizes before JavaScript can continue. The harmful pattern is repeated alternation: change something, measure, change another thing, measure again.

The web.dev guide to avoiding layout thrashing explains this read/write dependency. Prefer a measurement phase followed by a mutation phase when the measurements are logically independent of those mutations. That qualification matters: reading an expanded panel before expanding it measures a different state.

Draw the dependency in a review note. For each read, identify the element, the required state and the operation consuming its result. For each write, identify whether it can change any later measurement. This often exposes a repeated width read that could be performed once, but it can also reveal a genuine dependency that cannot safely be reordered.

A geometry read is not automatically expensive every time. If layout information is already current, the browser may not need a new layout. Optimize the observed sequence rather than banning an API throughout the codebase. The useful question is what changed before the measurement and whether the resulting calculation was avoidable.

Define what the measurement means

Before moving code, decide which box and coordinate system the feature needs. offsetWidth returns an integer layout width including padding, borders and a rendered vertical scrollbar. An element hidden with display: none, including through an ancestor, reports zero. Reading it earlier can therefore change both timing and correctness.

getBoundingClientRect() describes a rectangle relative to the viewport, with padding and borders included. Its positional values change when scrolling changes. A value saved while the page is stationary is not a permanent document coordinate. Do not replace a positioning calculation with a cached rectangle unless its invalidation conditions are explicit.

CSS sizing also matters. Assigning a measured outer width to an element using content-box adds that element's padding and border beyond the assigned width. With border-box, the assigned width includes them. An optimization that silently changes box sizing may appear faster only because it no longer produces the same layout.

Write these assumptions next to the code under review: visible or hidden state, relevant box, rounding tolerance, scroll reference and resizing behavior. A short contract makes it easier to decide whether a read can move. It also gives reviewers concrete edge cases instead of a vague instruction to check that the page still looks right.

Batch only independent reads and writes

Consider a feature that copies one visible reference element's width to several cards. If those card updates cannot change the reference element's width during the operation, take the measurement once. Then apply the stored value to the cards. This example assumes the cards use border-box and that integer precision is acceptable.

js
function matchCardWidths(reference, cards) {
  // Read before changing any card geometry.
  const width = reference.offsetWidth;

  // Cards use box-sizing: border-box.
  for (const card of cards) {
    card.style.width = `${width}px`;
  }
}

This is a dependency example, not a universal component implementation. Validate the reference before calling it and decide what a zero width should mean. Do not retain the value forever: a viewport change, different text or updated container can make it obsolete. The function takes a fresh snapshot each time the operation is deliberately requested.

For different measurements per card, first collect all required values into a separate array, then perform the writes in a second pass. Preserve the relationship between each element and its measurement. Do not read geometry again inside the write loop, including indirectly through utility functions, analytics hooks or callbacks triggered by your own abstraction.

Check whether CSS can express the relationship without measuring it at all. Shared grid tracks, flex alignment or a common container may already describe the desired sizing. Choose that route only when it preserves the product's behavior. A simpler layout contract is useful; replacing precise positioning with a visually approximate arrangement is a different change.

Keep real dependencies explicit

Some features need a size that exists only after a mutation. An expanding panel may need its new geometry to position another element. In that case, pretend batching that reads the old size is incorrect. Consider whether the dependent update can happen in a later rendering opportunity, or whether one intentional synchronous measurement is acceptable.

If the update can be delayed, define what the user sees in between and what happens if the action is reversed quickly. A queued callback should not reposition a panel that has already closed or been removed. Use component state or a cancellation strategy appropriate to the application, and test repeated clicks rather than only a single successful opening.

If the measurement must happen immediately, keep the dependency narrow. Apply related writes together, measure the required result once and reuse it for dependent calculations. Document why the synchronous read remains. The goal is to remove redundant cycles while maintaining correct behavior, not to make a trace contain no layout events.

A useful review distinguishes these cases:

Requirement Candidate approach Main correctness check
Several writes use one unchanged size Read once, then write Writes cannot alter the reference
Each item needs its current size Collect reads, then apply writes Stored values still describe the intended state
A new state must be measured immediately One explicit write/read boundary The result cannot be deferred safely
An element changes size independently Observe size changes Updates do not create a feedback loop

Do not treat scheduling as a cure

requestAnimationFrame() schedules a callback before a repaint. It does not promise that a write followed by a geometry read inside that callback will be free. Moving the same alternating loop into one callback preserves its dependency problem. Coordinate read and write phases across cooperating components rather than wrapping each component independently.

The callback is one-shot, and rendering callbacks can be paused in background tabs. Avoid using this scheduling mechanism as the only way to complete essential nonvisual state changes. If an animation advances over time, use the supplied timestamp rather than assuming that every display renders at the same refresh rate.

Likewise, delaying code is not equivalent to reducing its work. A long sequence of calculations can still occupy the main thread after the layout cycles have been removed. Make separate decisions about computation, rendering and interaction feedback. Keeping these causes distinct prevents one optimization from obscuring the next bottleneck.

Use observation without a feedback loop

ResizeObserver can notify a component when an observed element's box changes. It is useful when the requirement is to react to size changes rather than repeatedly poll geometry. Choose the observed box and the values used by the component deliberately; content size and border size are not interchangeable.

An observer callback that changes the observed element's size can trigger another observation. Guard against unchanged target values and circular dependencies. Merely moving a cyclic update to another frame can spread the problem across frames instead of solving it. Include the observer's cleanup when the component is destroyed or the observed element is replaced.

Containment is another separate decision. CSS containment can limit the scope of some rendering work, but it also changes layout behavior. Certain containment values introduce containing blocks and stacking contexts, while paint containment clips drawing outside the element's bounds. Test overlays and positioned descendants before adopting it. Do not add containment simply to silence a performance warning.

Verify the same result with less work

Repeat the original interaction with the same content, viewport and application state. Compare the number and duration of forced layout events and the time until useful feedback appears. Save both traces. A smaller amount of JavaScript with a later visible response is not sufficient evidence of a better experience.

Check narrow screens, long translated text, browser zoom, hidden-to-visible transitions and content that arrives after the initial render. Exercise keyboard activation and rapid repeated actions. These cases challenge cached geometry and queued callbacks in ways that a screenshot of the final desktop state will not reveal.

Keep the change when the dependency is understandable, the intended geometry is preserved and repeated recordings show less unnecessary work. Record remaining intentional measurements and their reasons. That evidence turns a one-off reflow cleanup into a maintainable rule for the component's next update.

Related guides