Skip to content

Instantly share code, notes, and snippets.

@alexcmgit
Last active January 21, 2020 22:14
Show Gist options
  • Save alexcmgit/a10074ceb1fb94257e99b3ae19e41e23 to your computer and use it in GitHub Desktop.
Save alexcmgit/a10074ceb1fb94257e99b3ae19e41e23 to your computer and use it in GitHub Desktop.
script that implements a window api to control the user's choice of theme with localstorage support and without the flash bug
//window.__theme: variable with the current theme: "dark" or "light"
//window.__setPreferredTheme: function that receives the new theme to be applied
//window.__onThemeChange: function that will be called every time the theme changes
(function() {
window.__onThemeChange = function() {};
function setTheme(newTheme) {
window.__theme = newTheme;
preferredTheme = newTheme;
document.body.className = newTheme;
window.__onThemeChange(newTheme);
}
var preferredTheme;
try {
preferredTheme = localStorage.getItem("theme");
} catch (err) {}
window.__setPreferredTheme = function(newTheme) {
setTheme(newTheme);
try {
localStorage.setItem("theme", newTheme);
} catch (err) {}
};
setTheme(preferredTheme || "dark");
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment