Implementing dark mode with no flash using inline script
The solution adds an inline script in src/app.html to set the theme class on <html> before hydration, preventing flashes of incorrect theme. It pairs with a Svelte store to toggle and persist the theme dynamically. This ensures the correct theme is applied immediately on page load.
The only way to avoid the “flash of the wrong theme” is to put the decision logic ahead of Svelte’s hydration. In SvelteKit the earliest place you control is src/app.html, so you can inline a tiny script that:
- reads a persisted choice from
localStorage
- falls back to the user’s
prefers-color-scheme
- applies a class/attribute to the root element before any CSS is evaluated
Then, inside your app you just keep that class in sync when the user toggles.
src/app.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script>
(() => {
const stored = localStorage.getItem('theme'); // 'light' | 'dark' | null
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const theme = stored ?? (prefersDark ? 'dark' : 'light');
const root = document.documentElement;
root.dataset.theme = theme; // optional, if you prefer [data-theme="dark"]
root.classList.toggle('dark', theme === 'dark'); // for Tailwind’s `dark:` or your own CSS
})();
</script>
%sveltekit.head%
</head>
<body class="bg-white text-slate-900 dark:bg-slate-900 dark:text-slate-50">
<div id="svelte">%sveltekit.body%</div>
</body>
</html>
A minimal store/toggle to keep things in sync after hydration:
// src/lib/theme.ts
import { writable } from 'svelte/store';
type Theme = 'light' | 'dark';
const getInitial = (): Theme => {
if (typeof document === 'undefined') return 'light';
const stored = localStorage.getItem('theme') as Theme | null;
if (stored) return stored;
return matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
};
export const theme = writable<Theme>(getInitial());
theme.subscribe((value) => {
if (typeof document === 'undefined') return;
document.documentElement.classList.toggle('dark', value === 'dark');
document.documentElement.dataset.theme = value;
localStorage.setItem('theme', value);
});
Usage in a component:
<script lang="ts">
import { theme } from '$lib/theme';
const toggle = () => {
theme.update((t) => (t === 'dark' ? 'light' : 'dark'));
};
</script>
<button on:click={toggle}>
Toggle { $theme === 'dark' ? 'Light' : 'Dark' }
</button>
Because the class/data attribute is set synchronously in app.html, the correct theme CSS is applied before SvelteKit hydrates, eliminating the flash of the wrong theme.