Search code examples
jquerydarkmode

How to stop page load flashing white when it set for dark mode


I have a script that reads the cookie and load theme according(night or light) mode

 $(document).ready(function () {
     var themeCookiesName = getCookie('Theme');
     if (themeCookiesName == 'dark') {
         document.body.classList.toggle("dark-theme")
     }
     else {
         document.body.classList.toggle("light-theme")
     }
 })

When it set to dark them, the page flashes white before it load the dark mode them. Any thoughts?


Solution

    1. Default to the light theme in your HTML to minimize scripting.
    2. Hide your site with CSS.
    3. Read the cookie.
    4. Conditionally apply the class to the body element.
    5. Show the site.

    $(function() { // shorthand for document.ready
    
      // const darkThemeEnabled = getCookie('Theme') === 'dark';
      const darkThemeEnabled = true; // for demo only - use the line above
    
      if (darkThemeEnabled) {
        document.body.classList.remove('light-theme');
        document.body.classList.add('dark-theme');
      }
    
      document.body.classList.remove('hidden');
    });
    body.hidden {
      display: none;
    }
    
    .dark-theme {
      background: #333;
      color: #eee;
    }
    <head>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>
    
    <body class="light-theme hidden">
      Content
    </body>