Home  >  Article  >  Web Front-end  >  How to Eliminate Dark Mode Flickering on Page Reload?

How to Eliminate Dark Mode Flickering on Page Reload?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-03 10:40:03384browse

How to Eliminate Dark Mode Flickering on Page Reload?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn