Skip to content

Commit

Permalink
fix flash of white page when preferring dark mode
Browse files Browse the repository at this point in the history
if you visit the blog for the first time, we have no theme-ui-mode stored in localStorage; so we read out the preferred color scheme, and if its dark mode, append theme-ui-dark to the document classList; this will avoid the flash; we don't need to do anything if:

- we prefer light mode, because light-mode is the default color scheme anyhow

- we already have something in localStorage, because the page will render correctly then; that is because theme-ui does this for us here (very similar to what I'm doing, heavily inspired by it): https://github.com/anonsecteaminc/theme-ui/blob/a11e7cba7c786cdbcc9a059e58a9e58841e9ad58/packages/color-modes/src/index.tsx#L331-L335

If I inject it manually, I'd have to remove the classList again; otherwise, the dark-mode toggle wouldn't do anything, as the toggle apparently doesn't remove or alter the html classList. I guess by using the same key (theme-ui-no-flash), this is now removed again automatically (it is, I checked!). So we now get the same no-flash behaviour, no matter if we have something in localStorage or not 🚀

theme-ui does something similar internally
  • Loading branch information
TkDodo committed Aug 29, 2021
1 parent b063769 commit f984059
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions gatsby-ssr.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { jsx } from 'theme-ui'

const noflash = `(function () {
try {
const hasLocalStorage = localStorage.getItem('theme-ui-color-mode')
if (
!hasLocalStorage &&
window.matchMedia('(prefers-color-scheme: dark)').matches
) {
document.documentElement.classList.add('theme-ui-dark')
}
} catch (err) {}
});`

export const onRenderBody = ({ setPreBodyComponents }) => {
setPreBodyComponents([
jsx('script', {
key: 'theme-ui-no-flash',
dangerouslySetInnerHTML: {
__html: noflash,
},
}),
])
}

0 comments on commit f984059

Please sign in to comment.