Sub topic 8
Saving the choice and preventing a flash of the wrong theme
This chapter assumes you already have the data-theme attribute and CSS custom properties from the previous chapters. It also assumes you can read and write DOM attributes with JavaScript. Here you will store the visitor's choice and apply it before the page first paints.
Why a saved choice is needed
A toggle that only changes data-theme forgets its state on reload. The page then falls back to the system setting. The browser's localStorage object stores small strings per origin and keeps them between visits, so it fits this job.
Saving the value is the easy part. The harder part is timing. The browser paints the page as soon as it has the HTML and CSS. If your theme code runs late, a visitor who chose dark mode sees a white page for a moment, then the dark one. This is the flash of the wrong theme.
Save the choice in the click handler
The toggle works out the current theme, switches to the other one, and writes it to storage:
const root = document.documentElement;
const button = document.querySelector("#theme-toggle");
button.addEventListener("click", () => {
const systemDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
const current = root.dataset.theme || (systemDark ? "dark" : "light");
const next = current === "dark" ? "light" : "dark";
root.dataset.theme = next;
localStorage.setItem("theme", next);
});The code stores only "light" or "dark". When nothing is stored, the CSS follows the system setting through the prefers-color-scheme media query.
Apply the saved theme before first paint
Put a small inline script in the <head>, before the stylesheet is applied to the page body. It runs while the browser is still parsing, so the attribute is set before anything is painted:
<script>
(function () {
var saved = localStorage.getItem("theme");
if (saved === "light" || saved === "dark") {
document.documentElement.setAttribute("data-theme", saved);
}
})();
</script>The script targets document.documentElement, which is the <html> element. That element exists as soon as parsing starts. <body> does not exist yet, so a script in the head cannot set an attribute on it.
Common errors
- Loading the script with
deferor at the end of<body>. The first paint can happen before it runs, and the flash returns. The theme script must be a plain inline script in the head. - Moving it to an external file. An external script is fine, but it must not use
deferorasync, and it adds a blocking request. Inline code avoids that request. - Storing anything other than the two known values. The
ifcheck ignores values like"purple"that come from old code or manual edits. - Not handling blocked storage. Some privacy settings make
localStoragethrow an error. An uncaught error in the head script stops it, and the page shows the system theme. Wrapping the calls intry/catchlets the page work either way.
A safer version of the head script:
<script>
(function () {
try {
var saved = localStorage.getItem("theme");
if (saved === "light" || saved === "dark") {
document.documentElement.setAttribute("data-theme", saved);
}
} catch (e) {
/* Storage is unavailable, so the system setting applies. */
}
})();
</script>Apply the same try/catch around localStorage.setItem in the click handler. Then the toggle still changes the theme for the current page view when saving fails.
What the script cannot cover
Without a saved choice, the CSS handles the system setting itself. The media query applies before first paint, so these visitors see no flash. Only a manual override needs the script, because only then does the theme depend on JavaScript.
Exercise
A visitor chose dark mode, but on every reload they see a brief white page before it turns dark. The theme script sits at the end of <body> and calls document.documentElement.setAttribute("data-theme", saved). What is wrong, and how do you fix it?
Show answer
The script runs after the browser has already painted the first frame with the default light colors. Move it into the <head> as a plain inline script, without defer or async, so data-theme is set before first paint. Wrapping the storage call in try/catch also keeps the page working when storage is blocked.