简体   繁体   中英

How to load dark theme without an delay

I am creating a webpage with dark-mode theme feature. I got my bundle.css where I have defined dark-mode class. I am using a javascript onclick event to set the cookie value and if the value is true after reload, javascript will generate class on the body element. However, if I reload the page, initially style will be loaded firstly so I can see the white background (light theme) for a few milliseconds and then the dark theme is loaded. And this delay is an issue .

I have also tried to add my JavaScript into the head, however, it did not solve the issue. I am using webpack in this project. Css, js and html files are divided into modules.

My question is: Is there any solution or way to load dark theme quickly without this delay or white blinking background by using javascript? Or backend is needed here? Thanks for your suggestions.

I think, the way to go is to replace the css file before it is loaded, I use the smarty template engine and create a variable which replaces the css path. Only problem is you need to reload once if you change the theme, so no instant color-swap.

I changed my way of handling dark-mode a bit: I still use a template engine which has a template for a page without content. The template engine excecutes a php script before displaying the website itself, so I check for dark mode first, then if it is enabled (eg a Cookie is set), I add the dark class to the body while displaying the html (So no delay). So every css class you want to change can be addressed like

body.dark .text1 
{
   color: #fffff;
}

so it will override the color of.text1. Using body.dark also allows you to instantly change the theme without reloading the page and with no delay. You can add and remove the dark class on the fly with JS and every class with body.dark as a prefix will change when you add the dark class to the body of the website. If you want to see a more detailed example, feel free to ask.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM