From 713510286c35eeb2829524b7615ab8f2b7c60690 Mon Sep 17 00:00:00 2001 From: Jon Peterson Date: Tue, 6 Sep 2022 18:11:29 -0600 Subject: [PATCH] apply dark mode before paint --- static/dark-theme.js | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/static/dark-theme.js b/static/dark-theme.js index 7241a978f..fd8086066 100644 --- a/static/dark-theme.js +++ b/static/dark-theme.js @@ -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() { @@ -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) { @@ -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) -}); +})