Load dark mode on static site without first loading light mode, or vice versa #3904
Replies: 4 comments 4 replies
-
One possibility would be to start with Another option is to store the user's preference in |
Beta Was this translation helpful? Give feedback.
-
They key is to both utilize LocalStorage and to take advantage of the event loop and how modern browsers load JavaScript. To save their theme into local storage, just use this JavaScript: localStorage.setItem('theme', 'dark') Then, add some JavaScript to the HTML to set the
So if you embed the JS directly into the HTML, you can set the class before the page is rendered. Here's the code snippet I include on my sites. You can just copy/paste it if you want. Note that users can set the theme to three states:
<script>
const setTheme = () => {
const savedTheme = localStorage.getItem('theme')
if (!savedTheme) localStorage.setItem('theme', 'system')
const { classList } = document.body
if (savedTheme === 'system' || !savedTheme) {
const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches
if (isDark) classList.add('dark')
} else if (savedTheme === 'dark') {
classList.add('dark')
}
}
setTheme()
</script> |
Beta Was this translation helpful? Give feedback.
-
Thanks for your help and the detailed advice. I don't think I can eliminate all the white flashes, at least in Firefox because I'm using a multi page app. When Firefox is waiting for a page to load as I navigate from one page to the next, the color of the empty window before the browser gets any data is white. Once data is loaded I can control what happens, but there is sometimes (depending on the network I guess) a gap between leaving one page and loading the next page and this is where the window flashes white. In a MPA this wouldn't be a problem. Does that sound correct? |
Beta Was this translation helpful? Give feedback.
-
One way to eliminate the white flash is to add |
Beta Was this translation helpful? Give feedback.
-
On a static site I'm using the dark mode feature introduced in v2.0 with the 'class' method, because I want to let users choose the theme regardless of the OS preference.
This relies on inserting a "dark" class into a DOM element, to make child elements load dark styles.
How can I do this without first loading the DOM and briefly displaying the light styles? It creates a flash of white before the dark mode is loaded. Because the site is static I can't serve HTML with a dark class already inserted.
Any ideas?
Thank you!
Awesome tool, btw. 🎉
Beta Was this translation helpful? Give feedback.
All reactions