Reading localstorage theme value before rendering components not working

I'm setting up a theme toggle. It can successfully set the theme in localstorage. When loading a specific theme from storage, there is a brief "flash" of the default theme before converting to the desired theme. Here is the function that loads the theme from localstorage. It's being loaded within the <Head/> tag from Solid Start.
function themeScript() {
try {
if (localStorage.theme === "dark" || (!("theme" in localStorage)
&& window.matchMedia("(prefers-color-scheme: dark)").matches)) {
document.documentElement.classList.add("dark");
document.querySelector('meta[name="theme-color"]')
?.setAttribute("content", "#0B1120");
} else {
document.documentElement.classList.remove("dark");
}
} catch (_) {}
return <></>;
}
function themeScript() {
try {
if (localStorage.theme === "dark" || (!("theme" in localStorage)
&& window.matchMedia("(prefers-color-scheme: dark)").matches)) {
document.documentElement.classList.add("dark");
document.querySelector('meta[name="theme-color"]')
?.setAttribute("content", "#0B1120");
} else {
document.documentElement.classList.remove("dark");
}
} catch (_) {}
return <></>;
}
The script always seems to run before the components but I'm not sure why I still get the flash. Is this a bug?
5 Replies
Brendan
Brendan2y ago
Quick questions: Do you get the same FOUC with a production build or just dev? Are you using purely css method based on the body class (or some css in js library)? Are you server rendering or client only? Solid-start on server?
RATIU5
RATIU5OP2y ago
Did not check it in prod but it does work there correctly. I am using TailwindCSS
Brendan
Brendan2y ago
I've heard that might just be a known vite dev server thing then.
RATIU5
RATIU5OP2y ago
I believe it currently is the client, if that is the default. I have not messed with server rendering yet That's interesting I was not aware of that. Guess that's not Solid's problem at that point
Brendan
Brendan2y ago
Others may know more ...but yeah a vite thing I think.
Want results from more Discord servers?
Add your server