Flickering site

On reloading, the site is prickly and flickering. I think it’s because of the dark theme script. But if you write a line at the beginning, before the tag does not exist script. Then the problem disappears. But that’s not right. All showed in the video. I hope it can be resolved.

https://youtu.be/c1ab5ER4qmw

dark.js:

// function to set a given theme/color-scheme
function setTheme(themeName) {
    localStorage.setItem('theme', themeName);
    document.documentElement.className = themeName;
    document.getElementById("sunimgid");
}

// function to toggle between light and dark theme
function toggleTheme() {
    if (localStorage.getItem('theme') === 'theme-dark') {
        setTheme('theme-light');
        document.getElementById("sunimgid").setAttribute("src", "/images/sunny.png");
    } else {
        setTheme('theme-dark');
        document.getElementById("sunimgid").setAttribute("src", "/images/moon.png");
    }
}

// Immediately invoked function to set the theme on initial load
(function () {
    if (localStorage.getItem('theme') === 'theme-dark') {
        setTheme('theme-dark');
        document.getElementById("sunimgid").setAttribute("src", "/images/moon.png");
    } else {
        setTheme('theme-light');
        document.getElementById("sunimgid").setAttribute("src", "/images/sunny.png");
    }
})();