
{ // Constants for use throughout the function const DARK_MODE_CLASS = ‘mariselle-dark-mode’; const DARK_READER_SCRIPT_ID = `${ DARK_MODE_CLASS }-script`; const SCRIPT_URL = ‘//cdnjs.cloudflare.com/ajax/libs/darkreader/4.9.34/darkreader.min.js’; const TOGGLE_BUTTON = document.querySelector(‘.mariselle-dark-button__toggle’); let pageRoot = document.querySelector(‘html’); // Function to add a script element to the page and return a promise that // resolves when the script has finished loading const addScriptElementToPage = (url) => { return new Promise((resolve) => { const script = document.createElement(‘script’); script.setAttribute(‘id’, DARK_READER_SCRIPT_ID); script.src = url; script.addEventListener(‘load’, () => resolve(true)); document.head.appendChild(script); }); }; // Function to check if the script element has been added to the page const hasScriptElement = () => document.querySelector(`#${ DARK_READER_SCRIPT_ID }`); // Function to add the script element to the page (if it doesn’t already exist) // and call the provided callback function const loadScriptElement = (callback) => !hasScriptElement() ? addScriptElementToPage(SCRIPT_URL).then(callback) : callback(); // Function to check if dark mode was enabled before the page was reloaded const isDarkModeEnabledBefore = () => Boolean(localStorage.getItem(DARK_MODE_CLASS)); // Function to check if dark mode is currently enabled const isDarkModeEnabled = () => pageRoot.classList.contains(DARK_MODE_CLASS); // Function to enable the Dark Reader library with specific options const enableDarkReader = () => DarkReader.enable({ brightness: 100, contrast: 90, sepia: 10 }); // Function to enable dark mode by adding the DARK_MODE_CLASS class to the page // and enabling the Dark Reader library const onDarkModeEnabled = () => { pageRoot.classList.add(DARK_MODE_CLASS); TOGGLE_BUTTON.checked = true; enableDarkReader(); }; // Function to toggle dark mode on or off const toggleDarkMode = () => { pageRoot.classList.toggle(DARK_MODE_CLASS); localStorage.removeItem(DARK_MODE_CLASS); DarkReader.disable(); if (isDarkModeEnabled()) { localStorage.setItem(DARK_MODE_CLASS, true); enableDarkReader(); } }; // Enable dark mode if it was enabled before the page was reloaded window.addEventListener(‘DOMContentLoaded’, () => { if (isDarkModeEnabledBefore()) { loadScriptElement(onDarkModeEnabled); } }); // Set up an event listener to toggle dark mode when the toggle element is clicked TOGGLE_BUTTON.addEventListener(‘click’, () => loadScriptElement(toggleDarkMode)); })(); ]]>