examples icon indicating copy to clipboard operation
examples copied to clipboard

Add inline script in head to prevent FOUC

Open FireIsGood opened this issue 2 years ago • 0 comments

Currently, all the examples will flash the wrong theme if you select a theme other than your preference (e.g. dark mode with prefers light or light mode with prefers dark).

The issue:

https://github.com/picocss/examples/assets/109556932/87031ac3-6062-4703-9639-e36d2cbbe78a

One way to fix this would be to include an inline script in the head section to check for a user's preference before displaying the body.

As an example of this, I have adapted the Astro Tutorial head script for this:

    <!-- Stop color scheme flash -->
    <script>
      // This must be inline to stop FOUC

      const localStorageKey = "picoPreferredColorScheme";
      const rootAttribute = "data-theme";

      const scheme = (() => {
        // Check for a stored theme
        if (typeof localStorage !== "undefined" && localStorage.getItem(localStorageKey)) {
          return localStorage.getItem(localStorageKey);
        }

        // Otherwise, check the user's color scheme preference
        return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
      })();

      // Set a data attribute for Pico
      document.documentElement.setAttribute("data-theme", scheme);

      document.querySelector("html")?.setAttribute(rootAttribute, scheme);
    </script>

I currently have the above script ready to put into all the v2 pages if this seems okay for a pull request.

Here is the fixed version, tested locally:

https://github.com/picocss/examples/assets/109556932/b7251700-7019-4eb7-afba-e8968dd2626d

Note that this is a lot harder to show on a local copy since there is almost no latency. I was able to check that the Fast 3g setting would sometimes show the FOUC while the script in the head completely removed it. If you are testing this for yourself, you may have to try many times to get it to flash the FOUC.

This issue is also reflected on the main site, though I haven't looked into a specific solution for it.

FireIsGood avatar Mar 25 '24 04:03 FireIsGood