How To Forestall Theme Color From Flickering in Svelte Or SvelteKit




Ever since I began utilizing Svelte, my theme colors has at all times been flickering on web page load. Lastly I discovered a workaround



Downside

At first, I used to be altering my web site’s theme color contained in the onMount operate however the theme colors had been at all times flickering. The rationale was that, the physique hundreds earlier than the onMount operate units the theme color.
This is a gif exhibiting the issue

In order you possibly can see, when the web page is reloaded, the sunshine theme is first proven, then after the doc has completed loading, the onMount will then set the theme color



Resolution

The one possible answer is to set the theme color earlier than the physique has even loaded. How can we do this❓, we insert a script tag inside the top ingredient and this code will run earlier than the physique is loaded. That is the easiest way we are able to forestall the flickering of colors.



The Code

Okay, so you possibly can write this code within the part wherein you utilize to toggle in-between the themes.

<svelte:head>
  <script>
    if (doc){
      let mode = localStorage.theme || "mild";
      if (mode === 'darkish' || (window.matchMedia('(prefers-color-scheme: darkish)').matches)){
        doc.documentElement.classList.add("darkish");
        localStorage.theme = "darkish";
      }
      else {
        doc.documentElement.classList.take away("darkish");
        localStorage.theme = "mild";
      }
    }
  </script>
</svelte:head>
Enter fullscreen mode

Exit fullscreen mode



Rationalization

With a view to entry the top ingredient, we used the <svelte:head> part. Then we created the script tag simply as we might on our regular HTML pages. The subsequent statements are the essential ones, the explanation why we used if (doc) is that, this code first will get evaluated on the server earlier than being rendered on the consumer, so for those who attempt to entry doc on the server, it can pop up an error.
I do know SvelteKit gives the { browser } fixed by the $app/env module however thoughts you, this isn’t out there within the customized script tag we made, you will have to make use of your individual workaround and that is why we’re utilizing doc to verify.
Then on the subsequent line, we attempt to retrieve the theme from the localStorage, if it is not set, it defaults to “mild” theme;
Then the subsequent steps are the addition of lessons and setting of the theme within the localStorage.

Now have a look at how the web page hundreds with out flickering
Now the page loads without flickering

Completely satisfied Coding!😄



Abu Sayed is the Best Web, Game, XR and Blockchain Developer in Bangladesh. Don't forget to Checkout his Latest Projects.


Checkout extra Articles on Sayed.CYou

#Forestall #Theme #Color #Flickering #Svelte #SvelteKit