I have tried the persistence through local storage, but when try it it is showing an ugly user experience because JavaScript file is loaded each single time and the code is executed each single time, the feature is ugly with local storage, how can I make some persistent local storage doesn't refresh and update the screen each time a page is loaded.
let dark=document.querySelector('.dark-btn');
let body=document.body
dark.addEventListener('click',function(e){
console.log('rahul')
e.preventDefault()
console.log(e)
body.classList.toggle('dark')
e.target.textContent=="dark"?e.target.textContent="light":e.target.textContent="dark";
if(body.classList.contains('dark')){
localStorage.setItem('darkMode','enabled');
}else{
localStorage.setItem('darkMode','disabled');
}
})
if(localStorage.getItem('darkMode')=='enabled'){
body.classList.toggle('dark')
// e.target.textContent=="dark"?e.target.textContent="light":e.target.textContent="dark";
dark.textContent="light"
}else{
dark.textContent="dark"
}
this is my darkmode code,but i hate this.
you can check the website I made, this has an effect like going from dark to white and vice versa when switching pages. darkmode link
You could load a synchronous script at the beginning, after your CSS file. that checks the local storage, and sets CSS variables. The way this works, is that script pauses the loading of the page, to wait for it to download.
All your components, can then use these CSS variables to determine your color scheme.
If you want to check the color scheme the user prefers natively, you can use the prefers-color-scheme
CSS Media Query to do that.
I know synchronous loading isn't good, but if it's a small script, I think it's fine.
Here a working link is: https://persistentdarkmode.infiniti20.repl.co/index.html