Sub topic 8
Avoiding the flash of the wrong theme
This chapter assumes you already have a working class-based dark variant (Tailwind v3 darkMode: 'selector' or a v4 @custom-variant), and a script that toggles the dark class on <html> from localStorage. You should be comfortable with the DOM, localStorage, and the order in which browsers parse HTML.
What the flash is
A flash of the wrong theme (sometimes called FOUC, flash of unstyled content, or in this case a flash of incorrect theme) happens when the page first paints in light mode, and then switches to dark a moment later. A user who chose dark sees a bright white frame, then the page darkens. On a dark-themed site viewed at night, this is jarring.
The cause is ordering. The browser can paint before your theme code has run. Your dark: utilities only match when the dark class is on an ancestor. If the class is not there yet at first paint, the browser renders the light styles.
Why the flash happens
Three common setups produce the flash:
- The theme code is in a bundled script loaded with
deferortype="module". Both run after the document is parsed, often after the first paint. - The theme code is at the end of
<body>. The content above it may already be painted. - A framework applies the theme after hydration, in an effect such as
useEffect. Server-rendered HTML arrives without the class, so it paints light first.
A related case is a page that is rendered ahead of time (static generation). The server has no access to localStorage, so it cannot know the user's choice. The HTML is always the same for everyone. Only client-side code can apply the right class, and it has to do so before the first paint.
The fix: a small blocking script in the head
The fix is to run a short script synchronously in <head>. A classic inline <script> without async, defer, or type="module" blocks parsing. The browser must execute it before it continues to the stylesheet and the body. By the time anything is painted, the class is already set.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script>
document.documentElement.classList.toggle(
"dark",
localStorage.theme === "dark" ||
(!("theme" in localStorage) &&
window.matchMedia("(prefers-color-scheme: dark)").matches),
);
</script>
<link rel="stylesheet" href="/styles.css" />
</head>
<body class="bg-white dark:bg-gray-900"></body>
</html>Read the condition in two parts:
localStorage.theme === "dark"is true when the user explicitly chose dark.!("theme" in localStorage) && matchMedia(...).matchesis true when the user has made no choice (the key is absent) and the operating system prefers dark.
If the user chose light, both parts are false, so toggle("dark", false) removes the class. If the user chose "system", the key is absent and the OS setting decides. This is the same three-state model from the previous chapter, evaluated once at load.
classList.toggle(name, force) with a second argument is the important detail. With force, it adds the class when the value is true and removes it when false. Without it, toggle would flip the current state, which is not what you want here.
Keep the script small and synchronous
Because the script blocks parsing, keep it tiny. It reads one storage key and one media query, which takes microseconds. Do not import modules, fetch data, or wait on promises in this script. Anything asynchronous reintroduces the gap you are trying to close.
The script must also be placed before the stylesheet link. The order matters less for correctness of the class (the class only has to exist before first paint), but placing it first guarantees it runs before the browser has any reason to render.
Keeping the page and the script in agreement
The head script and your toggle code are two copies of the same decision. If they drift apart, you get bugs that only appear on reload. A reasonable pattern is to put the decision in one small function, and have both places call the same logic.
Because the head script cannot import modules, the shared logic has to be inlined or duplicated. A pragmatic approach is to keep the head script as the source of truth for initial load, and write the toggle code so it only changes localStorage and then re-applies the same expression.
function applyTheme() {
document.documentElement.classList.toggle(
"dark",
localStorage.theme === "dark" ||
(!("theme" in localStorage) &&
window.matchMedia("(prefers-color-scheme: dark)").matches),
);
}
function setTheme(choice) {
if (choice === "system") {
localStorage.removeItem("theme");
} else {
localStorage.theme = choice;
}
applyTheme();
}
// React to OS changes while the user is on "system".
window
.matchMedia("(prefers-color-scheme: dark)")
.addEventListener("change", applyTheme);The change listener matters for users on "system". If they switch their operating system to dark at sunset while your page is open, the page follows. When the user has chosen light or dark explicitly, applyTheme ignores the OS value, so the listener is harmless.
Edge cases
`localStorage` can throw
In some browsers, with storage disabled or in certain private modes, reading localStorage throws a SecurityError. An exception in the head script stops it, and your page falls back to the light styles. Wrap the read in try/catch if you need to support these environments:
<script>
(function () {
var dark = false;
try {
var saved = localStorage.getItem("theme");
dark =
saved === "dark" ||
(saved === null &&
window.matchMedia("(prefers-color-scheme: dark)").matches);
} catch (e) {
dark = window.matchMedia("(prefers-color-scheme: dark)").matches;
}
document.documentElement.classList.toggle("dark", dark);
})();
</script>The function wrapper keeps dark and saved out of the global scope.
Content Security Policy
An inline script is blocked by a strict Content Security Policy (CSP) that does not allow 'unsafe-inline'. You have two options. Add a per-response nonce (script-src 'nonce-...') and put the same nonce on the script tag, or add a hash of the script's exact text to the policy. Moving the code to an external file with src also satisfies CSP, but a blocking external script costs a network request before first paint, so inline with a nonce or hash is usually better.
Frameworks that render on the server
Server-rendering frameworks often warn about a mismatch when the client changes an attribute that the server rendered differently. The head script changes class on <html> before hydration, so the framework sees a different attribute than the one it rendered. Most frameworks provide a way to mark that element as expected to differ (for example, React's suppressHydrationWarning on the <html> element). Check your framework's documentation. Theme libraries for popular frameworks exist and implement this same pattern, but the underlying mechanism is the script shown above.
Changing the theme with a transition
If your CSS has transition on colors, the first paint can still appear to animate from light to dark, because the class is applied while transitions are active. Avoid declaring broad transition-colors on body or *. If you want smooth toggling, apply the transition class only after load, for example by adding it in a requestAnimationFrame callback after the first frame.
Other things that look like the flash
Not every light frame is the theme script's fault:
- Browser default background. Before your CSS loads, the canvas is white. Setting
color-scheme: darkon:root(covered in a later chapter) tells the browser to use a dark default canvas. - A slow stylesheet. If the CSS arrives late, the page may paint unstyled. That is a loading problem, not a theme problem.
- Images with light backgrounds. A PNG with a white background will look bright on a dark page, even when the theme is correct.
Verifying the fix
Test the following cases in a browser, using the developer tools to simulate each condition:
| Case | Setup | Expected first paint |
|---|---|---|
| Explicit dark | `localStorage.theme = "dark"`, OS light | Dark |
| Explicit light | `localStorage.theme = "light"`, OS dark | Light |
| System, OS dark | Key removed, OS dark | Dark |
| System, OS light | Key removed, OS light | Light |
To see a flash that is too fast for your eye, open the Performance panel and record a reload with screenshots enabled, or throttle the CPU and network. If the first captured frame has the wrong colors, the class is being set too late. You can also temporarily add a debugger; statement or console.log to the head script and the later script, and compare the order they appear in the console.
Summary of the technique
- The flash is a timing problem: the
darkclass arrives after the first paint. - Run a small, synchronous, inline script in
<head>that sets the class fromlocalStorageandprefers-color-scheme. - Use
classList.toggle("dark", condition)with the second argument. - Handle storage errors, CSP, and hydration warnings where they apply.
- Re-run the same logic whenever the user changes the setting or the OS preference changes.
Exercise
A team's theme script lives in main.js, loaded as <script type="module" src="/main.js"></script> at the end of <body>. Users who chose dark see a white flash on every reload. Explain why, and describe the fix.
Show answer
Module scripts are deferred, so main.js runs after the document is parsed and often after the first paint. The page first paints with no dark class, so the light styles show, and then the script adds the class and the page repaints in dark. The fix is to put a short inline classic script in <head>, before the stylesheet, that reads localStorage.theme and prefers-color-scheme and calls document.documentElement.classList.toggle("dark", ...). It blocks parsing, so the class is set before the first paint. The rest of the toggle logic can stay in main.js.
Exercise
Why must the head script call classList.toggle("dark", condition) with a second argument instead of classList.toggle("dark")?
Show answer
Without the second argument, toggle flips the current state. If the class is already present, for example because it was set in the server-rendered HTML, the call would remove it when the user wants dark. With the force argument, the class is added when the condition is true and removed when false, so the result depends only on the saved choice and the OS preference.
Exercise
Your site sends the header Content-Security-Policy: script-src 'self'. After adding the inline head script, it no longer runs. Name two ways to allow it without enabling 'unsafe-inline'.
Show answer
Add a nonce: send script-src 'self' 'nonce-RANDOM' with a fresh random value on each response and put nonce="RANDOM" on the inline script tag. Or add a hash: compute the SHA-256 of the script's exact contents and add 'sha256-...' to script-src. Moving the code to an external file also works, but it adds a blocking network request.