I have a function that loads a different CSS file depending on a button click, The function switches the files fine and i`m using localStorage to keep the state for when the page reloads however when i navigate away from the page there is a 0.5 secong flash of the light CSS before switching to the dark version obviously this is only noticable in the Dark mode. I have posted the code below any suggestions on how to get rid of this delay would be appreciated. Thanks
<script>
function toggleTheme() {
link = document.getElementById("theme");
const bulb = document.getElementById('toggle-mdi');
let previousLink = localStorage.getItem('autosave')
if (!previousLink) {
previousLink = "{% static 'css/base.css' %}?v{{ settings.VERSION }}"
}
if (previousLink == "{% static 'css/base.css' %}?v{{ settings.VERSION }}") {
link.setAttribute('href', "{% static 'css/dark.css' %}?v{{ settings.VERSION }}");
localStorage.setItem("autosave", "{% static 'css/dark.css' %}?v{{ settings.VERSION }}");
bulb.setAttribute('class', "mdi mdi-lightbulb")
console.log(localStorage.getItem('autosave'))
} else {
link.setAttribute('href', "{% static 'css/base.css' %}?v{{ settings.VERSION }}");
localStorage.setItem("autosave", "{% static 'css/base.css' %}?v{{ settings.VERSION }}");
bulb.setAttribute('class', "mdi mdi-lightbulb-on");
console.log(localStorage.getItem('autosave'))
}
};
$( document ).ready(() => {
let mode = localStorage.getItem('autosave')
let bulb_icon = document.getElementById('toggle-mdi');
if (!mode) {
mode = "{% static 'css/base.css' %}?v{{ settings.VERSION }}"
} else {
document.getElementById('theme').setAttribute('href', mode)
console.log(mode)
}
if (mode === "{% static 'css/base.css' %}?v{{ settings.VERSION }}") {
bulb_icon.setAttribute('class', "mdi mdi-lightbulb-on");
} else if (mode === "{% static 'css/dark.css' %}?v{{ settings.VERSION }}") {
bulb_icon.setAttribute('class', "mdi mdi-lightbulb");
}
});
</script>