Light mode flicker on page load when darkmode enabled
The goal of the post is to show a way to set or remove the dark class of the body container of a page before rendering has occured.
The universal document <head> tag manager unhead that is povering the vue project is a powerful tool.
It does have option to set the content of the <script> like:
script: [{ src: 'https://example.com/script.js' }].
How ever instead of the sourece (src) attribute a the script-elements .innerHTML can be set directly. Here is as snippet that is also using multi-line JS/TS string quotation with ``.
Unhead first argument: UseHeadInput<T>
{
"title": "AUC",
"meta": [
{ name: 'description', content: 'AUC Oy - Software Consultancy' }
],
"bodyAttrs": {
class: "h-full bg-white antialiased dark:bg-zinc-900",
}
"script": [ {
innerHTML: `console.log("Hello: Setting the dark class to root element");
if (localStorage.theme === 'dark'
|| (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
document.documentElement.classList.add('dark')
} else {
document.documentElement.classList.remove('dark')
}`
} ],
}