SolidJSS
SolidJSโ€ข4y agoโ€ข
11 replies
RATIU5

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 <></>;
}

The script always seems to run before the components but I'm not sure why I still get the flash. Is this a bug?
Was this page helpful?