saadeghi / theme-change

Change CSS theme with toggle, buttons or select using CSS custom properties and localStorage
https://codepen.io/saadeghi/pen/OJypbNM
MIT License
1.42k stars 46 forks source link

Optimization for page load theme-change delay #28

Open farukcan opened 1 year ago

farukcan commented 1 year ago

We must change theme before pageload event to avoid theme changing delay.

  1. Step
if (typeof exports != "undefined") {
    module.exports = {
        themeChange: themeChange
    }
} else {
    var selectedTheme = localStorage.getItem("theme"); // ADD line 1
    if(selectedTheme){ // ADD line 2
        document.documentElement.setAttribute("data-theme",selectedTheme); // // ADD line 3
    } // // ADD line 4
    themeChange(true);
}
  1. Step Add async attribute. And add this element to <head> . It must be first loaded script that no need wait for page load. <script async crossorigin="anonymous" src="./theme-change.js"></script>

Thanks for your library!

saadeghi commented 1 year ago

Thank you my friend.
I will try this soon.

It's a challenge because on one hand, we don't want to block the page loading by the script, on the other hand, we want to apply the theme before page loading...

Also, many people instead of using a <script> tag, want to install it as a NPM package and import it with React, Vue, etc.

JieyueCoding commented 1 year ago

Thank you all. Following Mr. Farukcan's comment, I temporarily added the following code to the <head> of my index.html. This also avoids delays.

<script async crossorigin="anonymous">
var selectedTheme = localStorage.getItem("theme");
if(selectedTheme) {
    document.documentElement.setAttribute("data-theme", selectedTheme);
}
</script>
jamaluddinrumi commented 1 year ago

hi @JieyueCoding it does not work for me

i mean, it need to be checked from blank tab each, not from already visited website

the glitch is still there

can i see your demo, please?