Hugo Tunius Hugo Tunius - 6 months ago 12
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

hidden
on the body which is changed to
light
or
dark
when
DOMContentLoaded
fires. Unfortunately this still causes one paint to happen before the class is changed. By putting the JS in
<head>
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
body
before
DOMContentLoaded
fires?

Thanks

Answer

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>
<html>
<head>
    <meta charset="UTF-8">
    <title>Test</title>
    <style>
        html.dark body{background:black;}
    </style>
    <script>
        document.getElementsByTagName('html')[0].setAttribute('class', 'dark');
    </script>
</head>
<body>

</body>
</html>
Comments