Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

plue's avatar
Level 1

how to avoid flickering in reload

How can i prevent my website flicked when it's darkmode when reload? I have a website that has dark mode but when i reload the default theme flicked for a seconds then go dark mode. How can i prevent that? here is my code html:

<div class="theme">
   <ion-icon id="theme-toggle" name="moon-outline" class="switch"></ion-icon>
 </div>

script:

var theme;

    $(".switch").click(function() {
        console.log("dark-mode")
        $("body").toggleClass("dark-mode");
        if($("body").hasClass("dark-mode")) {
            $(".switch").attr("name", "sunny-outline");
            theme = "DARK";
        } else {
            $(".switch").attr("name", "moon-outline");
            theme = "LIGHT";
        }

        localStorage.setItem("PageTheme", JSON.stringify(theme));
    })

    let getTheme = JSON.parse(localStorage.getItem("PageTheme"));
        console.log(getTheme)

    if (getTheme === "DARK") {
        document.body.classList = "dark-mode";
        $(".switch").attr("name", "sunny-outline");
    }
0 likes
1 reply
Snapey's avatar
Snapey
Best Answer
Level 122

suggest you get the mode from local storage in the head of the page rather than defer to later scripts, and set the classes on the body without waiting for jquery to download and boot (so use native javascript)

1 like

Please or to participate in this conversation.