How to Prevent White Background Flickering During Dark Mode Reload?

Patricia Arquette
Release: 2024-11-04 02:58:01
Original
991 people have browsed it

How to Prevent White Background Flickering During Dark Mode Reload?

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:

  1. Add Script to :
<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>
Copy after login
  1. Move Scripts to End of :

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>
Copy after login
  1. Update JavaScript for Toggle Functionality:

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>
Copy after login

Additional Notes:

  • You can combine the above JavaScript code into a single .js file if desired.
  • Consider using a spinner or loading animation during the initial theme transition to improve the user experience.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template