#flash of unstyled content
5 messages · Page 1 of 1 (latest)
hmmmm where did my message go
The flash of unstyled content (FOUC) you're experiencing might be due to the timing of when your theme script is loaded and executed. In your current setup, the theme script is loaded at the end of the navigation process, after the new page has fully loaded in the browser. This could cause a flash of the light theme version of the site before the theme toggle script runs and checks which theme it should use on the page.
To prevent this, you can modify your script to check for, and if necessary set, the dark mode earlier in the navigation process. You can create a function that will run in response to the astro:after-swap event. This function will check the browser’s localStorage for the dark theme when the first page is visited and immediately after the new page has replaced the old page, before the DOM elements are painted to the screen.
Here's an example of how you can modify your script:
<script is:inline>
function applyTheme() {
localStorage.theme === 'dark'
? document.documentElement.classList.add("dark")
: document.documentElement.classList.remove("dark");
}
document.addEventListener('astro:after-swap', applyTheme);
applyTheme();
</script>
With this modification, every page change that uses the <ViewTransitions /> router for client-side navigation (and therefore has access to the astro:after-swap event) will be able to detect theme: dark from the browser’s localStorage and update the current page accordingly before the page is rendered for the viewer. This should help prevent the flash of unstyled content you're experiencing in dark mode.
😦