Hugo Tunius Hugo Tunius - 8 months ago 15
HTML Question

Modify body's classes before first paint

this is a long shot and I suspect what I am trying to do is ultimately impossible.

I am trying to implement a dark/light mode switch on my website. The thing is that the site is just static files on S3 and as such there's no server side I have control of in play.

The problem I have run into is loading the correct theme when a new page is loaded, because the value is stored in local storage I need to fetch it and change the value on page load.

My current approach uses an initial class of

on the body which is changed to
fires. Unfortunately this still causes one paint to happen before the class is changed. By putting the JS in
I was able to circumvent the problem in Safari and Chrome, but not Firefox.

The problem with the initial paint happening is that it causes an extremely jarring flashing, especially when dark more is enabled as the screen quickly goes from white to black.

So my question is wether it's possible to somehow change the classes of



Instead of adding the class to the body, you can add it to the <html> element, from the <head> section.

That way, the class will be applied before the body loads. Example code:

<!DOCTYPE html>
    <meta charset="UTF-8">
        html.dark body{background:black;}
        document.getElementsByTagName('html')[0].setAttribute('class', 'dark');