J’ai fait quelques recherches pour identifier quelle est la “meilleure” méthode pour implémenter un “Theme Switcher” pour un projet SvelteKit SSR.

J’ai trouvé cet article pertinent : How to implement a cookie-based dark mode toggle in SvelteKit.

En particulier, cette partie :

One might save the preference in the browser’s local storage. With every page visit, we check with it if a theme is saved. This works well, but it will cause the website to flash because it takes some time to download and execute the JavaScript.

et un peu plus loin dans l’article :

After publishing this post, I was made aware that we can make the localStorage solution work also without flashing. Then we do not need any server-side logic and can also work with prerendered pages (such as a blog). In fact, the initial theme can be retrieved (via a media query or a localStorage value if it exists) in a script tag which is directly put into the body element of the app.html.

Voici une mise en pratique dans cet exemple : https://github.com/ScriptRaccoon/sveltekit-darkmode-toggler-localstorage/.

J’ai utilisé cette technique pour https://sklein.xyz.


Tous les tags présents dans la note :