How to Eliminate White Background Flickering During Dark Mode Reload
When implementing dark mode in an app, it's crucial to address the issue of white background flickering upon page reload. This unsightly flickering occurs when the page initially loads in light mode before switching to dark mode.
Solution: Prevent Page Rendering
The key to resolving this flickering issue lies in blocking page rendering. By placing a small script tag within the
section of the document, you can halt the DOM parser process. This allows the JavaScript interpreter to assign the data-theme attribute to the element before continuing the page rendering process.Implementation:
<code class="html"><script> // Set the theme in <HEAD> before any other tag. const setTheme = (theme) => { theme ??= localStorage.theme || "light"; document.documentElement.dataset.theme = theme; localStorage.theme = theme; }; setTheme(); </script></code>
Position all other scripts in a non-render-blocking manner, right before the closing tag:
<code class="html"><script src="js/index.js"></script> <!-- Other <script> tags here --> </body> </html></code>
Inside your JavaScript file, adjust the code as follows:
<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>
Additional Notes:
The above is the detailed content of How to Prevent White Background Flickering During Dark Mode Reload?. For more information, please follow other related articles on the PHP Chinese website!