#Morph animation flickering
3 messages · Page 1 of 1 (latest)
This flickering issue might be due to the theme toggle script loading at the end of the navigation process, after the new page has fully loaded in the browser. There may be a flash of the light theme version of the site before this theme toggle script runs and checks which theme it should use on the page.
To prevent this, you can check for, and if necessary set, 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 to check the browser’s localStorage for dark theme will run 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 is an example of how you can do this:
<script is:inline>
function setDarkMode(document) {
let theme = localStorage.darkMode ? 'dark' : 'light';
document.documentElement.dataset.theme = theme;
}
setDarkMode(document);
document.addEventListener('astro:before-swap', ev => {
// Pass the incoming document to set the theme on it
setDarkMode(ev.newDocument);
});
</script>
This script ensures the browser’s light or dark mode preference in localStorage is carried over to the new page. The astro:before-swap event can be used to make changes before the swap occurs. The newDocument property on the event represents the incoming document.
You can find more details about this in the Astro documentation (https://docs.astro.build/en/guides/view-transitions/#astrobefore-swap).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@frigid hull kapa.ai is still learning and improving, please let us know how it did by reacting below