Skip to content

Commit

Permalink
apply dark mode before paint
Browse files Browse the repository at this point in the history
  • Loading branch information
whois-jon-peterson authored and cxong committed Sep 14, 2022
1 parent 3c560f1 commit 7135102
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions static/dark-theme.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ const DARK_THEME_KEY = 'startInDarkTheme';

function setDarkTheme() {
document.body.classList.add(DARK_THEME_CLASS);
document.getElementById('dark-theme-button').innerHTML = "Light Theme";
setThemeButtonText("Light Theme");
}

function setLightTheme() {
document.body.classList.remove(DARK_THEME_CLASS);
document.getElementById('dark-theme-button').innerHTML = "Dark Theme";
setThemeButtonText("Dark Theme");
}

function toggleDarkTheme() {
Expand All @@ -21,7 +21,19 @@ function toggleDarkTheme() {
}
}

window.addEventListener('load', function() {
/**
* Safely modify theme button text only if it exists
* @param {string} text label for button
*/
function setThemeButtonText(text) {
const button = document.getElementById('dark-theme-button')
if (button) {
button.innerHTML = text
}
}

// enable dark theme as soon as possible so first paint is already dark mode
(function () {
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => {
if (localStorage.getItem(DARK_THEME_KEY) === null) {
if (event.matches) {
Expand All @@ -34,6 +46,11 @@ window.addEventListener('load', function() {
if (localStorage.getItem(DARK_THEME_KEY) === 'true' || window.matchMedia('(prefers-color-scheme: dark)').matches) {
setDarkTheme();
}
})();

// handle theme button label and listener once DOM fully loaded
window.addEventListener('DOMContentLoaded', function () {
const isDarkTheme = document.body.classList.contains(DARK_THEME_CLASS)
setThemeButtonText(isDarkTheme ? "Light Theme" : "Dark Theme")
document.getElementById('dark-theme-button').addEventListener('click', toggleDarkTheme)
});
})

0 comments on commit 7135102

Please sign in to comment.