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?

2
  • 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. Commented Jun 25, 2017 at 20:46
  • Maybe disable the current css file before appending the new one? A bit old but some ideas: stackoverflow.com/questions/3182840/… Commented Jun 25, 2017 at 20:53

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.