Reputation: 2392
I'm trying to change the bootstrap CSS style (I'll call it theme) of an HTML page. I want to switch between row
s and card
s style, which I have managed to do with some JavaScript and DOM manipulation. I also save the current theme in the local storage, so when refreshing the page I can set the theme chosen. I do all of this in the window.onload
event.
The problem arises when I refresh the page: the theme is set correctly but it first shows the default one, and then it renders the one in localStorage
.
How can I avoid this delay when setting the correct theme?
Upvotes: 0
Views: 170
Reputation: 370619
Two ideas:
It's generally better to listen for the DOMContentLoaded instead. The load
event will fire only after all images, media, etc are downloaded. This may well happen far after the initial page load, so the browser has had time to do the initial paint in the meantime, meaning that the load
event visibly occurs somewhat later. In contrast, DOMContentLoaded fires when the DOM is parsed and interactable, without additional delays. But, the DOM is not necessarily parsed immediately - there may be a bit of delay between (for example) the loading of the first half of the DOM and the loading of the rest, so in addition:
At the start of the page, hide the main page content (say, the article) with CSS, perhaps with article { display: none }
or something of the sort. Then, in your DOMContentLoaded listener, fiddle with the DOM / CSS and change the theme as desired, and then make the article visible. This will ensure that the initial paint that the user sees will be painted with the desired theme, rather than seeing one theme, shortly followed by the actual desired theme.
If you can make all theme changes with CSS alone, it would be even better to set the correct stylesheet immediately, in the <head>
, before the body content has started to load. (Don't put the CSS part in a DOMContentLoaded
listener.) But this is only an option if your DOM changes don't involve Javascript.
Upvotes: 5