App
← TIL
TIL

Avoiding the dark-mode flash on first paint

css theming

To avoid a flash of the wrong theme, the theme has to be applied before the page paints. An inline script in <head> reads the saved preference (or the system setting) and toggles the dark class on <html> synchronously:

const saved = localStorage.getItem("theme")
const dark = saved ? saved === "dark" : matchMedia("(prefers-color-scheme: dark)").matches
document.documentElement.classList.toggle("dark", dark)

That’s exactly what ThemeScript.astro does.