A quick post for an improvement I made to the website:
I recently tackled an annoying flicker issue when using dark mode on my website. The problem occurred because the dark mode class (dark-mode) was being added via a script inside the body. This caused a delay before the class was applied, resulting in a brief flash of light mode before dark mode took effect.
To fix this, I moved the script into the <head>
tag. This change ensures the script runs before any content is
rendered, blocking the page from showing in light mode while the script is being applied. While blocking script
execution is usually avoided, this script is lightweight and critical for preventing the flicker.
Here’s how I implemented the solution:
I created a wrapper component for the page <head>
that automatically appends the dark mode setup script:
const setupDarkModeScript = `
(() => {
const darkMode = localStorage.getItem("website.darkMode");
const prefersDarkMode = window.matchMedia("(prefers-color-scheme: dark)").matches;
if (darkMode === "true" || (darkMode === null && prefersDarkMode)) {
document.documentElement.classList.add("dark-mode");
}
})();
`.trim();
export const PageHead: React.FC<React.PropsWithChildren> = ({ children }) => (
<>
{children}
<script>{setupDarkModeScript}</script>
</>
);
Having the script as a string ensures I don't run into any SSR issues.
Overall, I’m happy with this solution. The flicker is gone, and dark mode now loads seamlessly.