2

I would like to allow my users to choose between a “light” theme (the default) and a “dark” theme, which is provided by the addition of another CSS file.

Here’s the JavaScript code. As you can see, I tried to provide for additional themes in the future.

var themes = {
    "dark": "HTML/css/dark-theme.css"
};

var themeCssLink = document.createElement('link');
themeCssLink.setAttribute('rel', 'stylesheet');
document.getElementsByTagName('head')[0].appendChild(themeCssLink);

var theme = localStorage.getItem('theme');
if (!(theme in themes))
    theme = null;
if (theme !== null)
    themeCssLink.setAttribute('href', themes[theme])

The problem with this is that the page renders before the dark theme CSS loads, causing a bright white flash, which I would like to know how to prevent.

Another thing I tried was to put a dummy LINK element in the HTML:

<link href='' rel='stylesheet' type='text/css' id='theme-css'>

and then just modifying the href in the JavaScript:

var themeCssLink = document.getElementById('theme-css');
var theme = localStorage.getItem('theme');
if (!(theme in themes))
    theme = null;
if (theme !== null)
    themeCssLink.setAttribute('href', themes[theme]);

Unfortunately this has the same effect.

How do I convince the browser to block rendering until the theme CSS file is loaded?

Timwi
  • 65,159
  • 33
  • 165
  • 230
  • What is the order of includes? Thus when is the javascript included into the page? The rendering should halt on encountering javascript. That is why it sometimes recommended to put the include at the end of the body. – puelo Jun 25 '17 at 20:46
  • Maybe disable the current css file before appending the new one? A bit old but some ideas: https://stackoverflow.com/questions/3182840/removing-or-replacing-a-stylesheet-a-link-with-javascript-jquery – wazz Jun 25 '17 at 20:53

1 Answers1

0

Just put your javascript script before your css, so that your theme is loaded before your main css.

If you do that you have to be carreful about your main.css, so that it doesn't override your theme css loaded before.

Gatsbill
  • 1,760
  • 1
  • 12
  • 25