Dark Mode Flickers White on Reload: Blocking Rendering for Seamless Transition
The issue of dark mode flickering on page reload arises when using local storage to persist user preferences. To resolve this, it's recommended to block page rendering initially and then apply the theme preferences.
Solution: Block Page Rendering
Implement this small script within the
section before any other tags:<code class="html"><script> // Set this in <HEAD> top before any other tag. const setTheme = (theme) => { theme ??= localStorage.theme || "light"; document.documentElement.dataset.theme = theme; localStorage.theme = theme; }; setTheme(); </script></code>
This script initializes the theme based on local storage or defaults to "light".
Non-Blocking Scripts
Place all other scripts before the closing tag in a non-render-blocking manner:
<code class="html"><script src="js/index.js"></script> <script src="other_scripts.js"></script> <!-- Closing </body> and </html> go here --></code>
Customization in index.js
In the index.js file, handle theme toggling:
<code class="javascript">const elToggleTheme = document.querySelector('#dark-mode-button input[type="checkbox"]'); elToggleTheme.checked = localStorage.theme === "dark"; elToggleTheme.addEventListener("change", () => { const theme = elToggleTheme.checked ? "dark" : "light"; setTheme(theme); });</code>
This code updates the theme when the checkbox is toggled. You can alternatively place this script in a separate JS file.
By implementing these changes, the page rendering will be blocked initially, allowing the theme preferences to be set promptly. This eliminates the white flickering effect and provides a seamless transition between light and dark modes.
The above is the detailed content of How to Eliminate Dark Mode Flickering on Page Reload?. For more information, please follow other related articles on the PHP Chinese website!