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?