next-themes icon indicating copy to clipboard operation
next-themes copied to clipboard

Fix flash on page load when using value mapping

Open ErAz7 opened this issue 2 years ago • 1 comments

When using value mapping there is a flash on page load (on both development and production). This is due to updateDOM function returning empty ('') and thus the attribute on <html> is not set

Source of bug

The source of this bug is here: https://github.com/pacocoursey/next-themes/blob/8fc17e2a53aeb9e5918f8b9152795e56712ea862/src/index.tsx#L233

The condition if (resolvedName) is not met when called here: https://github.com/pacocoursey/next-themes/blob/8fc17e2a53aeb9e5918f8b9152795e56712ea862/src/index.tsx#L252 leaving the else block useless

The produced scrept in ThemeScript is as follows:

!(function () {
  try {
    var d = document.documentElement,
      n = "data-theme",
      s = "setAttribute";
    var e = localStorage.getItem("theme");
    if ("system" === e || (!e && true)) {
      var t = "(prefers-color-scheme: dark)",
        m = window.matchMedia(t);
      if (m.media !== t || m.matches) {
        d[s](n, "theme-dark");
      } else {
        d[s](n, "theme-light");
      }
    } else if (e) {
      var x = { light: "theme-light", dark: "theme-dark" };
    }
  } catch (e) {}
})();

The last if block (else if (e)) doesn't do anything on DOM

Fix

Adding || literal to the condition in updateDOM function to also call setAttribute when value is passed literally

Before

2023-01-14_1-29-47

After

2023-01-14_1-32-22

ErAz7 avatar Jan 13 '23 21:01 ErAz7

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated
next-themes-basic ✅ Ready (Inspect) Visit Preview 💬 Add your feedback Jan 13, 2023 at 9:54PM (UTC)
next-themes-tailwind ✅ Ready (Inspect) Visit Preview 💬 Add your feedback Jan 13, 2023 at 9:54PM (UTC)

vercel[bot] avatar Jan 13 '23 21:01 vercel[bot]

Fixed in new script approach.

pacocoursey avatar Mar 13 '24 16:03 pacocoursey