You ship a dark mode toggle. It works — click it, the page goes dark, click again, it goes back. You're happy. Then you refresh the page with dark mode saved, and for one frame the screen is a blinding white rectangle before it snaps to black.
It's not every browser. It's not every time. But it's there often enough that someone on your team files it as "dark mode flickers" and you go looking for the bug in prefers-color-scheme .
It's not there. The media query is working exactly as designed. The bug is somewhere you didn't think to look: the order your scripts run in, relative to the one paint you don't get a second chance at.
The fix everyone reaches for first
Here's the toggle, built the way most tutorials show it:
// theme-toggle.js — loaded normally, no special placement const stored = localStorage . getItem ( " theme " ); const theme = stored ?? ( matchMedia ( " (prefers-color-scheme: dark) " ). matches ? " dark " : " light " ); document . documentElement . dataset . theme = theme ;
document .…