-
Notifications
You must be signed in to change notification settings - Fork 65
Description
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.