Skip to content

Commit

Permalink
fix: move dark mode script to avoid FOUC
Browse files Browse the repository at this point in the history
  • Loading branch information
EATSTEAK committed Dec 17, 2023
1 parent 5449823 commit 1f1b6c1
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 21 deletions.
23 changes: 23 additions & 0 deletions src/components/BaseHead.astro
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,26 @@ const { title, description, image = '/blog-placeholder-1.jpg' } = Astro.props;
<meta property="twitter:title" content={title} />
<meta property="twitter:description" content={description} />
<meta property="twitter:image" content={new URL(image, Astro.url)} />

<!-- Dark mode -->
<script is:inline>
const theme = (() => {
if (
typeof localStorage !== "undefined" &&
localStorage.getItem("theme")
) {
return localStorage.getItem("theme");
}
if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
return "dark";
}
return "light";
})();

if (theme === "light") {
document.documentElement.classList.remove("dark");
} else {
document.documentElement.classList.add("dark");
}
window.localStorage.setItem("theme", theme);
</script>
21 changes: 0 additions & 21 deletions src/layouts/Layout.astro
Original file line number Diff line number Diff line change
Expand Up @@ -24,26 +24,5 @@ const page = pathname.slice(1);
<Header page={page} client:only />
<slot />
<Footer />
<script is:inline>
const theme = (() => {
if (
typeof localStorage !== "undefined" &&
localStorage.getItem("theme")
) {
return localStorage.getItem("theme");
}
if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
return "dark";
}
return "light";
})();

if (theme === "light") {
document.documentElement.classList.remove("dark");
} else {
document.documentElement.classList.add("dark");
}
window.localStorage.setItem("theme", theme);
</script>
</body>
</html>

0 comments on commit 1f1b6c1

Please sign in to comment.