Sub topic 8
Saving the Choice and Preventing a Flash of the Wrong Theme
This chapter assumes you already have a theme built from semantic custom properties, with a data-theme attribute on the root element that overrides prefers-color-scheme. It also assumes you can read and write DOM attributes and use localStorage. Here you will make the user's choice persist across visits, and you will stop the page from briefly showing the wrong colors while it loads.
Why the choice must be saved
A toggle that only changes an attribute on the live document forgets everything on reload. The next page load starts from the system setting again. A user who chose dark on a light system would see light mode on every new page.
You need somewhere to keep the choice. For a static site, the usual place is localStorage. It is a key-value store, scoped to the origin (scheme, host, and port), that survives browser restarts. It stores strings only, and reading it is synchronous.
The stored value has three possible meanings:
| Stored value | Meaning | Effect on the page |
|---|---|---|
| `"light"` | The user forced light | `data-theme="light"` is set |
| `"dark"` | The user forced dark | `data-theme="dark"` is set |
| nothing | The user has no preference | No attribute, so `prefers-color-scheme` decides |
Store "system" by removing the key, not by writing the string "system". That way, "no saved choice" and "follow the system" are the same state, and you never have to handle a third stored string.
Why the flash happens
The browser paints as soon as it has HTML and render-blocking CSS. Your toggle script usually runs later, often because it is loaded with defer at the end of the page. In that gap the page renders with the default (light) tokens, then your script sets data-theme="dark", and the page repaints. The user sees a white flash. This is sometimes called a flash of incorrect theme.
The fix is to set the attribute before the first paint, which means running a small script early, in the <head>.
The early script
The script must be inline and synchronous. An inline script has no network delay. A script without defer, async, or type="module" blocks parsing until it finishes. Those three attributes all let the browser paint first, which brings back the flash.
<script>
(function () {
try {
var saved = localStorage.getItem("theme");
if (saved === "light" || saved === "dark") {
document.documentElement.setAttribute("data-theme", saved);
}
} catch (e) {
// Storage is blocked. Fall back to the system setting.
}
})();
</script>The try/catch is not decoration. Reading localStorage can throw a SecurityError when the user blocks site data, or in some embedded and private browsing contexts. An uncaught error here would stop the script, but the page would still render, just with no saved theme. Catching it keeps the behavior predictable.
The script checks for exactly "light" or "dark" and ignores anything else. A stale value from an older version of your site, or from a user editing storage by hand, then cannot produce a data-theme attribute that matches no CSS rule.
Where it goes in the page
Put the script in <head>, before the stylesheet and before any content. This skeleton also includes a color-scheme meta tag, which tells the browser to use a matching canvas color before your CSS arrives.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>Theme demo</title>
<script>
(function () {
try {
var saved = localStorage.getItem("theme");
if (saved === "light" || saved === "dark") {
document.documentElement.setAttribute("data-theme", saved);
}
} catch (e) {}
})();
</script>
<link rel="stylesheet" href="theme.css">
<script src="theme-toggle.js" defer></script>
</head>
<body>
<label for="theme-select">Theme</label>
<select id="theme-select">
<option value="system">System</option>
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
<h1>Hello</h1>
</body>
</html>The script runs on <html> before <body> exists. That is why it uses document.documentElement, which is available at that point. document.body would be null.
The toggle script
The early script only reads. A second script handles changes. It supports all three choices, and it removes the stored key for "system".
const STORAGE_KEY = "theme";
const root = document.documentElement;
const select = document.querySelector("#theme-select");
function readChoice() {
try {
const value = localStorage.getItem(STORAGE_KEY);
return value === "light" || value === "dark" ? value : "system";
} catch (e) {
return "system";
}
}
function applyChoice(choice) {
if (choice === "system") {
root.removeAttribute("data-theme");
} else {
root.dataset.theme = choice;
}
}
function saveChoice(choice) {
try {
if (choice === "system") {
localStorage.removeItem(STORAGE_KEY);
} else {
localStorage.setItem(STORAGE_KEY, choice);
}
} catch (e) {
// Storage is blocked or full. The theme still applies for this visit.
}
}
select.value = readChoice();
select.addEventListener("change", () => {
applyChoice(select.value);
saveChoice(select.value);
});Setting select.value on load keeps the control in sync with what the early script applied. Without that line, a user with a saved dark theme would see the dark page with the menu showing "System".
When the choice is "system", removing the attribute hands control back to the media query. If the operating system switches to dark at sunset, the page follows without any JavaScript, because the CSS handles it.
Why the attribute is removed, not set to "system"
Your CSS only has rules for data-theme="light" and data-theme="dark", plus the media query with :not([data-theme="light"]). A value of "system" would match none of the explicit rules, so it would act like no attribute anyway. But it would also be a value your selectors must know about forever. Removing the attribute keeps the CSS contract to two values.
Edge cases
Several tabs open
If a user changes the theme in one tab, other tabs of your site keep the old theme until reload. The browser fires a storage event in the other tabs, so you can keep them in sync. The event does not fire in the tab that made the change.
window.addEventListener("storage", (event) => {
// event.key is null when storage is cleared entirely.
if (event.key === STORAGE_KEY || event.key === null) {
const choice = readChoice();
applyChoice(choice);
select.value = choice;
}
});Add this to the toggle script. It reuses the same readChoice function, so a removed key correctly becomes "system".
Storage is unavailable
When storage is blocked, the choice cannot persist. The page still works. The theme applies for the current page, then resets to the system setting on the next load. Do not show an error for this. If you want to be careful, test with the private mode of a browser that restricts storage.
The `file://` and subdomain scope
localStorage is per origin. A user who picks dark on www.example.com has no saved choice on docs.example.com. If you need one choice across subdomains, store it in a cookie with a Domain attribute instead. That has a cost, covered in the next section.
Transitions on load
If you animate color changes with transition: background-color 0.3s, the early script can still cause visible fading when styles resolve. Add the transition rule only after load, for example by adding a class to the root in a requestAnimationFrame callback after the page is ready. Otherwise the first paint can fade from light to dark. Switching themes by hand should still animate, so enable transitions after the first frame, not never.
Alternatives to localStorage
| Approach | Strength | Weakness |
|---|---|---|
| `localStorage` plus inline head script | Simple, no server needed | The server cannot know the theme, so server-rendered HTML always starts neutral |
| Cookie read by the server | The server can render the right `data-theme` in the HTML, so no script is needed for first paint | Sent with every request, needs server code, may need consent handling |
| Hide the page until the script runs | Hides the flash entirely | Delays content and breaks without JavaScript. Avoid it. |
For a static site, the inline script is the standard answer. For a server-rendered site, a cookie lets the server write <html data-theme="dark"> directly, which removes the need for the early script.
Checking your work
- Choose dark, reload, and confirm no light flash appears. Throttle the CPU in developer tools to make any flash easier to see.
- Choose "System", reload, and confirm the
data-themeattribute is gone andlocalStoragehas nothemekey. - Open two tabs, change the theme in one, and confirm the other follows.
- Set
localStorage.themeto"purple"in the console and reload. The page should fall back to the system setting.
Exercise
A page stores the theme in localStorage and applies it in a script tag with the defer attribute in the head. Users with a saved dark theme see a brief white flash on each load. Why does it happen, and what is the smallest change that fixes it?
Show answer
A deferred script runs only after the document has been parsed, so the browser can paint the page with the default light tokens first and then repaint dark when the script sets data-theme. The fix is to move the small read-and-apply code into an inline script without defer, async, or type="module" in the head, so it sets the attribute on document.documentElement before the first paint. The larger toggle code can stay deferred.
Exercise
A user selects "System" in your menu. Should you write the string "system" to localStorage? Explain what you should do and what the page does afterward.
Show answer
No. Remove the theme key with localStorage.removeItem and remove the data-theme attribute from the root element. The CSS then has no explicit override, so the prefers-color-scheme media query decides, and the page follows the operating system even if it changes while the page is open. This also keeps the CSS limited to the two values light and dark.
Exercise
You add a storage event listener to sync tabs. You test by changing the theme in one tab and watching that same tab, and nothing extra happens. Is the listener broken?
Show answer
No. The storage event fires only in other tabs or windows of the same origin, never in the tab that made the change. The tab that changed the theme already applied it in its own change handler. To test the listener, open a second tab and watch that one.