Skip to content

Instantly share code, notes, and snippets.

@vzhou842
Created June 19, 2021 00:00
Show Gist options
  • Save vzhou842/08bed68cdd70785d83384487bfcdfbde to your computer and use it in GitHub Desktop.
Save vzhou842/08bed68cdd70785d83384487bfcdfbde to your computer and use it in GitHub Desktop.
// This is the code we're inserting at the top of our page
(function() {
// Update the current theme to either 'light' or 'dark'
function setTheme(theme) {
window.__theme = theme;
// TODO: do other logic to update theme here
console.log('Theme updated:', theme);
};
// Save the user's explicit theme preference.
// We're attaching this to window so we can access it anywhere.
// We'll need it later in this post.
window.__setPreferredTheme = function(theme) {
setTheme(theme);
try {
localStorage.setItem('preferred-theme', theme);
} catch (e) {}
};
// Is there a Saved Theme Preference in localStorage?
let preferredTheme;
try {
preferredTheme = localStorage.getItem('preferred-theme');
} catch (e) {}
// Is there an Operating System Preference?
let darkQuery = window.matchMedia('(prefers-color-scheme: dark)');
// PICK THE INITIAL THEME
// 1. Use the theme from localStorage, if any
// 2. Use the OS theme, if any
// 3. Default to light
setTheme(preferredTheme || (darkQuery.matches ? 'dark' : 'light'));
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment