The load event tracks when the page is loaded, you can start loading the desired style earlier, which we will take from localStorage
// Сохранение темы в localStorage const saveCssTheme = function (theme) { localStorage.cssTheme = theme; } // Получение темы из localStorage, либо дефолтной const getCssTheme = function () { return localStorage.cssTheme || 'default-theme'; } // Загрузка css файла const loadCssTheme = function (theme) { const link = document.createElement('link'); link.id = theme; link.type = "text/css"; link.rel = 'stylesheet'; link.href = `/css/${theme}.css`; // если мы уже загрузили стили, то не нужно делать это еще раз if(document.getElementById(theme)) return; document.head.appendChild(link); } // Установка темы const setCssTheme = function(theme) { loadCssTheme(theme); saveCssTheme(theme); document.body.setAttribute('class', theme); } // Использование при загрузке страницы document.addEventListener("load", function () { const theme = getCssTheme(); setCssTheme(theme); });
In css let the default be the default theme, the rest will look like this
body.theme a {} // стиль примениться к элементу a, только если у body есть класс theme body.theme h1 {}
UPD
Buttons to turn on
<ul class="colors"> <li onclick="setCssTheme('theme0')">style0</li> <li onclick="setCssTheme('theme1')">style1</li> <li onclick="setCssTheme('theme2')">style2</li> </ul>
UPD
The class for body necessary so that css-themes do not overlap each other, if you manage without it, just delete the corresponding code
If the initial download does not work, try this:
document.onload = function () { const theme = getCssTheme(); setCssTheme(theme); };
Or in the question add, then use my code