🧩 HTML5: Fix a details Element’s Content Flashing Open for One Frame on Page Load Because a Script Toggles the open Attribute Before Hydration Finishes
A details element renders closed by default unless the open attribute is present in the markup, and some frameworks set that attribute via JavaScript shortly after the initial HTML paints. If the server-rendered HTML ships without open but client-side code decides whether it should start open based on some stored or computed state, there’s a brief window between first paint and that script running where the element shows its default closed state, then visibly snaps open a frame or two later, producing a jarring flash on every page load for any panel that’s supposed to start expanded.
🔎 The Problem
Server-rendered HTML:
<details> <!-- no open attribute: renders closed by default -->
<summary>Shipping Details</summary>
...content...
</details>
Client script (runs after hydration, roughly 80-150ms later):
if (shouldStartOpen) { detailsEl.setAttribute('open', ''); }
Visible result: closed for about 100ms, then pops open -
a noticeable flash on every load, worse on slower devices
✅ Fix: Decide the Initial State Before the First Paint, Not After
- Decide the initial open/closed state on the server and render the open attribute directly in the server-rendered HTML whenever you know the answer at render time, so there’s nothing left for client-side script to toggle after the fact.
- If the decision genuinely depends on client-only state, use a tiny inline script placed immediately after the details element in the HTML — before the rest of the page’s JS bundle loads — so the attribute gets set in the same paint rather than one hydration cycle later.
- Hide the details element’s content with CSS until a hydrated marker is present if you can’t avoid a client-side decision entirely, trading a brief invisible panel for an invisible-then-correct one instead of a visible flash of the wrong state.
🚨 Why This Is Dangerous
- A visible flash on every page load reads as a bug to users even when the final state is correct, and on a page with several details panels making this same mistake, the cumulative flashing can make the whole page feel noticeably less polished than it actually is.
Anything a user sees paint, then watches change, registers as broken — even when the final state was always the right one.
