A dark theme without a flash
The theme is set by a class on the root element before render — otherwise the visitor sees a white screen.
A light screen when the dark theme is chosen is the most noticeable bug when switching appearance. It happens when the theme is applied by a script that runs after the styles have loaded.
The loading order
- The document markup.
- A small inline script in
<head>: it reads the saved choice and sets the class on<html>. - The styles.
The first two steps require no network requests, so the class is applied before the first paint.
The source of truth is localStorage
Once a visitor has chosen a theme by hand, the system setting no longer takes part. While nothing
is in storage, prefers-color-scheme is used.
One switch — one state
When the theme button is rendered in two places (in the header and in the mobile menu, say), both copies read the same value and update on the same event. Otherwise the buttons drift apart.
Check: turn on the dark theme, reload the page and make sure there is no white flash.
- accessibility
- frontend