Having your website’s dark/light mode flicker on each page load is not a nice user experience. A white flash when in dark mode is particularly disturbing for someone reading in the dark. It could wake up a kid or spouse!
Fortunately, this is easily solved.
First, you must make sure that the first thing that the browser does when rendering your website is to check in which mode to render. This is achieved by running javscript code immediately in the
<head> tag of your page.
<script> tags in your
.astro files. This is usually really nice, but not if the code is checking for dark/light mode - this will create a flicker on each page load, as the script is put in an external script file by Astro.
To prevent Astro from optimizing your script tag, your must use the is:inline directive. This tells Astro to leave your script tag as it is and not bundle it in an external file.
// The configured mode is stored in local storage
const isDarkMode = localStorage.getItem('darkMode');
// Set theme to 'dark' if darkMode = 'true'
const theme = isDarkMode === 'true' ? 'dark' : '';
// Put dark class on html tag to enable dark mode
document.querySelector("html").className = theme;
Now, your script will be the first thing that runs! I hope this helps you create better websites with dark/light mode using Astro!