This is a great question about implementing dark mode in SvelteKit while avoiding the "flash of unstyled content" (FOUC) or in this case, a flash of the wrong theme. This is a common problem when dealing with theme switching in web apps.
The key insight is that we need to:
- Run JavaScript BEFORE the page renders anything
- This needs to happen before Svelte hydrates
- We can do this with an inline script in the
<head> of app.html
- Check both localStorage (user preference) and matchMedia (system preference)
- Set the appropriate CSS class on the document root
Let me create a comprehensive solution:
- app.html - Contains the inline script in the head
- src/lib/theme.js - A composable/store for theme management
- src/routes/+page.svelte - Example component showing how to use the theme
- app.css - CSS with CSS variables and dark mode styles
Here's the implementation:
<!-- src/app.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width" />
%sveltekit.head%
<!-- Inline script to prevent theme flash -->
<script>
// Get stored theme preference or check system preference
function getInitialTheme() {
const stored = localStorage.getItem('theme');
if (stored) {
return stored;
}
// Check system preference
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
return 'dark';
}
return 'light';
}
const theme = getInitialTheme();
document.documentElement.classList.toggle('dark', theme === 'dark');
// Store the initial preference
if (!localStorage.getItem('theme')) {
localStorage.setItem('theme', theme);
}
</script>
</head>
<body>
<div id="sveltekit-app" />
</body>
</html>
The inline script runs synchronously before any rendering occurs, checking localStorage for a saved preference first, then falling back to the system's color scheme preference via matchMedia. It immediately applies the appropriate class to the document root and persists the preference if it's the first visit.
Beyond this initialization, I need to handle theme management throughout the app with a store to track state, CSS variables for dark mode styling, and a UI component that lets users switch between themes.
Dark Mode in SvelteKit Without Flash
Here's a complete solution that prevents theme flashing by running inline script before hydration:
1. src/app.html - Inline Theme Detection
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head%
<!-- Prevent theme flash - runs before anything renders -->
<script>
(function() {
const theme = (() => {
// 1. Check user preference in localStorage
const stored = localStorage.getItem('theme');
if (stored === 'light' || stored === 'dark') {
return stored;
}
// 2. Check system preference
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
return 'dark';
}
// 3. Default to light
return 'light';
})();
// Set class and store preference
document.documentElement.classList.toggle('dark', theme === 'dark');
localStorage.setItem('theme', theme);
})();
</script>
</head>
<body data-sveltekit-preload-data="hover">
<div id="sveltekit-app"></div>
</body>
</html>
2. src/lib/theme.ts - Theme Store
import { writable } from 'svelte/store';
import { browser } from '$app/environment';
export type Theme = 'light' | 'dark';
function createThemeStore() {
let initialTheme: Theme = 'light';
if (browser) {
initialTheme = (localStorage.getItem('theme') as Theme) || 'light';
}
const { subscribe, set } = writable<Theme>(initialTheme);
return {
subscribe,
toggle: () => {
set(prev => {
const newTheme: Theme = prev === 'light' ? 'dark' : 'light';
if (browser) {
localStorage.setItem('theme', newTheme);
document.documentElement.classList.toggle('dark');
}
return newTheme;
});
},
set: (theme: Theme) => {
if (browser) {
localStorage.setItem('theme', theme);
document.documentElement.classList.toggle('dark', theme === 'dark');
}
set(theme);
}
};
}
export const theme = createThemeStore();
3. src/app.css - Styling with CSS Variables
:root {
color-scheme: light;
--bg-primary: #ffffff;
--bg-secondary: #f5f5f5;
--text-primary: #1a1a1a;
--text-secondary: #666666;
--border-color: #e0e0e0;
--accent: #3b82f6;
}
html.dark {
color-scheme: dark;
--bg-primary: #1a1a1a;
--bg-secondary: #2d2d2d;
--text-primary: #ffffff;
--text-secondary: #b0b0b0;
--border-color: #404040;
--accent: #60a5fa;
}
body {
background-color: var(--bg-primary);
color: var(--text-primary);
transition: background-color 0.3s, color 0.3s;
}
/* Example: Card component */
.card {
background-color: var(--bg-secondary);
border: 1px solid var(--border-color);
border-radius: 0.5rem;
padding: 1rem;
transition: background-color 0.3s;
}
/* Optional: smooth transitions only after initial load */
html.transitions-enabled body,
html.transitions-enabled .card {
transition: background-color 0.3s, color 0.3s;
}
4. src/routes/+layout.svelte - Enable Transitions
<script>
import { onMount } from 'svelte';
import { theme } from '$lib/theme';
import '../app.css';
// Enable transitions after hydration to prevent animation on load
onMount(() => {
document.documentElement.classList.add('transitions-enabled');
});
</script>
<slot />
5. src/routes/+page.svelte - Example Usage
<script>
import { theme } from '$lib/theme';
</script>
<main class="container">
<h1>Welcome to Dark Mode</h1>
<button
on:click={() => $theme === 'light'
? theme.set('dark')
: theme.set('light')}
class="theme-toggle"
>
{$theme === 'light' ? '🌙 Dark' : '☀️ Light'}
</button>
<div class="card">
<p>Current theme: <strong>{$theme}</strong></p>
</div>
</main>
<style>
.container {
max-width: 800px;
margin: 0 auto;
padding: 2rem;
}
.theme-toggle {
padding: 0.5rem 1rem;
background-color: var(--accent);
color: white;
border: none;
border-radius: 0.25rem;
cursor: pointer;
font-weight: 500;
transition: opacity 0.2s;
}
.theme-toggle:hover {
opacity: 0.9;
}
.card {
margin-top: 2rem;
}
</style>
Key Features ✨
| Feature | Description |
|---|
| No Flash | Inline <script> runs before rendering |
| Persistent | Stores preference in localStorage |
| System Sync | Respects prefers-color-scheme if no preference stored |
| TypeScript | Full type safety |
| Reactive | Svelte stores for reactive updates |
| Smooth | CSS transitions after hydration (avoid FOUC animations) |
| SSR Safe | Uses browser check to prevent SSR errors |
How It Works 🎯
-
Inline Script (app.html) runs BEFORE anything renders:
- Checks localStorage → System preference → Defaults to light
- Sets
dark class on <html>
- Eliminates the flash
-
Theme Store syncs theme state across components
-
CSS Variables enable easy theme switching
-
Transitions only enable after hydration to prevent load animations
This approach ensures zero flash and a seamless user experience! 🚀