vendredi 30 juillet 2021

An alternative to store dark-mode information in cookies or local-storage for faster reload

I'm creating a static website to host my notes on the web. On that site, I have implemented a dark-mode feature based on a flag (e.g flag=0 means dark and flag=1 means light). Now, to save the previous browsing theme of the user, I'm saving the flag value in two ways...

  1. Using Cookies
  2. Using LocalStorage

For Cookies, I'm using the following function to extract the flag value...

function getCookie(cname) {
        let name = cname + "=";
        let decodedCookie = decodeURIComponent(document.cookie);
        let ca = decodedCookie.split(';');
        for (let i = 0; i < ca.length; i++) {
            let c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
                document.cookie = "darkflag = 1";
            }
        }
        return "1";
    }

and for localStorage,

function getLS(cname) {
        let val = localStorage.getItem(cname);
        if (val !== null && val !== ''){
            return val;
         }
        else {
                return "1";
                localStorage.setItem("darkflag", "1");
            }
        }

Testing both these ways using local-host works perfectly, but when I've hosted them using netlify ( Site that uses Cookie and Site that uses localStorage ), I'm facing a performance issue in refreshing the webpage after setting the dark mode. It reloads into the light mode, takes a little time (~1.2-1.5 sec) to read the flag data, and displays the correct theme.

How can I remove this issue? Is there any alternative way to store the dark flag data?

Any help/ suggestion is highly appreciable.

Thank you.


P.S. My dark mode function looks something like this...

function darkmode() {
    var darkflag = (getLS('darkflag'));
    var r = document.querySelector(':root');
    if (darkflag == 0) {
        r.style.setProperty('--bg', '#040407');
        r.style.setProperty('--font', '#eee');
        r.style.setProperty('--sidebarbg', '#111');

 and so on...
}



Aucun commentaire:

Enregistrer un commentaire