DEV Community

Cover image for Detecting dark mode on every request 🌓

Detecting dark mode on every request 🌓

Bryce Dorn on August 08, 2022

I'm a huge proponent of dark color schemes! Aside from causing less eye strain due to emitting less blue light, dark pixels drain less battery life...
Collapse
 
darkwiiplayer profile image
Info Comment hidden by post author - thread only accessible via permalink
𒎏Wii 🏳️‍⚧️

Wouldn't it be easiest (and most widely supported) to just insert a bit of blocking javascript at the start of the page that optionally adds a class to the <body> element?

Collapse
 
bryce profile image
Bryce Dorn

That would still cause a flicker as described above. The header would enable the server to generate the appropriate static content so there's no client-side blocking.

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

That would still cause a flicker as described above

How so?

Thread Thread
 
bryce profile image
Bryce Dorn

For the blocking javascript to run (via <script> tag) the browser needs to load the HTML for the page. This HTML won't have a theme initially applied to it, so the page could switch from light to dark after this script runs.

Thread Thread
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

This HTML won't have a theme initially applied to it

Yea but that's the point of the javascript block; apply the theme as the page is loading, how would that still cause any flickering?

Thread Thread
 
bryce profile image
Bryce Dorn

as the page is loading

The JS doesn't run until the page is loaded. Here's an example.

Collapse
 
bluefalconhd profile image
Hayes Dombroski

Safari uses webkit. Safari will get this header really close to the time it is released in webkit.

Some comments have been hidden by the post's author - find out more