JoshBee
cat 11ty-dark-mode.md

11ty Dark Mode

Setting up dark mode

I was trying to figure out how to setup dark mode on my 11ty site, and kept having issues with flickering on page refresh no matter what I tried. (Claude and ChatGPT both also said everything looked correct). I was stumped and started digging into the generated code. The thing was, I couldn't find out where my script was that set the initial theme on the body.

So where was it?

Well 11ty is just too good at building all of the javascript together. Instead of keeping the script at the top of the <head> component, it had bundled all of the javascript into a single file, and then loaded it at the bottom of the body. This loads the javascript last after the entire page is loaded causing the flash.

The fix

Add eleventy:ignore to the <script> tag so that it is not bundled into the remaining javascript. This lets the script be the first thing that loads, and then the remainder bundled javascript executes after the page is rendered. (1)

Full code example

<head>
 <script eleventy:ignore>
  (() => {
   try {
    const stored = localStorage.getItem('theme');
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;

    if (stored && stored !== 'system')   {
     document.documentElement.classList.add(stored);
    } else {
     document.documentElement.classList.add(prefersDark ? 'dark' : 'light');
    }
   } catch {}
  })();
 </script>
 
 ...
</head>

Resources

(1) 11ty Bundle Docs