Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add inline script in head to prevent FOUC #18

Open
FireIsGood opened this issue Mar 25, 2024 · 0 comments
Open

Add inline script in head to prevent FOUC #18

FireIsGood opened this issue Mar 25, 2024 · 0 comments

Comments

@FireIsGood
Copy link

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:

Peek.2024-03-24.21-39.mp4

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:

Peek.2024-03-24.21-45.mp4

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant