Skip to content

Commit f9b2cd0

Browse files
authored
Fix dark mode switcher flash bug (#4167) (#4174)
Ref: #4167
1 parent 245a7a9 commit f9b2cd0

3 files changed

Lines changed: 21 additions & 7 deletions

File tree

layouts/partials/html-head.hbs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,4 +34,6 @@
3434
{{#each site.feeds}}
3535
<link rel="alternate" href="/{{ ../site.locale }}/{{ link }}" title="{{ text }}" type="application/rss+xml">
3636
{{/each}}
37+
38+
<script src="/static/js/themeSwitcher.js"></script>
3739
</head>

static/js/main.js

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -48,13 +48,6 @@
4848
;(function () {
4949
const themeAttr = 'data-theme'
5050
var darkThemeSwitcherElement = document.querySelector('.dark-theme-switcher')
51-
var isInDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
52-
53-
if (getTheme() == null) {
54-
setTheme(isInDarkMode ? 'dark' : 'light')
55-
} else {
56-
setTheme(getTheme())
57-
}
5851

5952
darkThemeSwitcherElement.addEventListener('click', function () {
6053
var currentTheme = getTheme()

static/js/themeSwitcher.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
;(function () {
2+
const themeAttr = 'data-theme'
3+
const isInDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
4+
5+
if (getTheme() == null) {
6+
setTheme(isInDarkMode ? 'dark' : 'light')
7+
} else {
8+
setTheme(getTheme())
9+
}
10+
11+
function setTheme (theme) {
12+
document.querySelector('html').setAttribute(themeAttr, theme)
13+
window.localStorage.setItem('theme', theme)
14+
}
15+
16+
function getTheme () {
17+
return window.localStorage.getItem('theme')
18+
}
19+
})()

0 commit comments

Comments
 (0)