2

I'm looking to give users the ability to switch a theme and I have 2 seperate style sheets, 1 for each theme.

I do something like this to switch it

    toggleTheme() {
        if (usingWhiteTheme) {
            $('link[href="white.css"]').attr('href', 'dark.css');   
            usingWhiteTheme = false;        
        } else {
            $('link[href="dark.css"]').attr('href', 'white.css');    
            usingWhiteTheme = true;
        }
    }

However it causes hideous flicker the first time as it loads the file from the server. After that it switches without a flicker.

How can I preload this style and then load it from the cache? Should I even use cache or is there someway more reliable for users that turn off cache? Can I stuff it into local storage?

parliament
  • 21,544
  • 38
  • 148
  • 238
  • 1
    Look at http://stackoverflow.com/questions/1059793/pre-loading-external-files-css-javascript-for-other-pages and in general search for "precaching css files" – Yuriy Galanter Feb 28 '14 at 18:40

3 Answers3

2

Here is the way I have observed in Dojo toolkit.

theme1

 document.body.className = "theme1";

for theme2

 document.body.className = "theme2";

Your CSS should be modular like below

in theme1.css

 .theme1 div{
     background-color : green
 }

in theme2.css

 .theme2 div{
     background-color : yellow;
 }
redV
  • 684
  • 1
  • 9
  • 26
0

Poor man solution would be to put an hidden iframe at the bottom of the page which points to a page...which includes all css files and all other static files u want to be cached. Up to you to figure how to make that happen only once though.

Itay Moav -Malimovka
  • 52,579
  • 61
  • 190
  • 278
0

For my purpose I was able to get around the flicker without preloading. Im using a premade bootstrap template it comes with a different css file for each theme. So instead of preloading, (which I tried and still kept having a flicker for some reason), what I did was created a new .less or .scss file with this:

 body.white-theme {
     //pasted the entire theme's css here
 }

This just wraps every style in the theme with body.white-theme in the compiled css.

Now I can safely load both stylesheet sheets at once and switch the class.

parliament
  • 21,544
  • 38
  • 148
  • 238