Skip to content

Commit 6804d66

Browse files
committed
fix(theme): prevent theme flicker on page load
- Move theme initialization script to right after the body tag is available - Apply stored theme synchronously before content renders - Fixes flash of light theme
1 parent e64be02 commit 6804d66

File tree

1 file changed

+18
-17
lines changed

1 file changed

+18
-17
lines changed

site/lib/src/layouts/dash_layout.dart

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,24 @@ ga('send', 'pageview');
190190
'class': [?bodyClass, ...defaultBodyClasses].toClasses,
191191
},
192192
),
193+
// The theme setting logic should remain before other scripts to
194+
// avoid a flash of the initial theme on load.
195+
raw('''
196+
<script>
197+
const prefersDarkMode = window.matchMedia('(prefers-color-scheme: dark)');
198+
199+
const storedTheme = window.localStorage.getItem('theme') ?? 'light-mode';
200+
if (storedTheme === 'auto-mode') {
201+
console.log(storedTheme, document.body.classList, prefersDarkMode.matches);
202+
document.body.classList.add(
203+
'auto-mode',
204+
prefersDarkMode.matches ? 'dark-mode' : 'light-mode',
205+
);
206+
} else {
207+
document.body.classList.add(storedTheme);
208+
}
209+
</script>
210+
'''),
193211
raw('''
194212
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-5VSZM5J" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
195213
'''),
@@ -225,23 +243,6 @@ ga('send', 'pageview');
225243
]),
226244
const DashFooter(),
227245
]),
228-
// The theme setting logic should remain before other scripts to
229-
// avoid a flash of the initial theme on load.
230-
raw('''
231-
<script>
232-
const prefersDarkMode = window.matchMedia('(prefers-color-scheme: dark)');
233-
234-
const storedTheme = window.localStorage.getItem('theme') ?? 'light-mode';
235-
if (storedTheme === 'auto-mode') {
236-
document.body.classList.add(
237-
'auto-mode',
238-
prefersDarkMode.matches ? 'dark-mode' : 'light-mode',
239-
);
240-
} else {
241-
document.body.classList.add(storedTheme);
242-
}
243-
</script>
244-
'''),
245246
GlobalScripts(),
246247
],
247248
);

0 commit comments

Comments
 (0)