Preventing dark mode from flashbanging you in Astro
Published on 2024/04/05
I kept getting flashbanged while making the dark mode / light mode toggle on this site, so I went looking for how I could fix this.
Turns out, astro does some optimization and bundling magic to all the javascript code it finds in the codebase.
This is usually great, but that optimization was making the screen flicker every time the page loaded because the script that checks for the right mode got put into an external script file which had to be loaded every single time.
To fix this, I just had to tell astro to inline the javascript that checked for the right mode. You can do this by slapping a is:inline
directive onto the script tag as shown below:
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="generator" content={Astro.generator} />
<title>Code, Freedom, & Life - foss.life</title>
👉🏽 <script is:inline>
document.documentElement.classList.toggle(
"dark",
localStorage.theme === "dark" ||
(!("theme" in localStorage) && window.matchMedia("(prefers-color-scheme: dark)").matches),
);
</script>
</head>