Reputation: 238
sorry if my title was phrased poorly. I have a toggle for light theme and dark theme. I'm able to save the selected theme in a cookie with jquery like so:
jQuery(document).ready(function ($) {
$(".theme__switch").on("click", () => {
$(".theme__switch").toggleClass("active");
$("body").toggleClass("dark__theme");
$.cookie("toggle", $(".theme__switch").hasClass("active"));
});
if ($.cookie("toggle") === "true") {
$(".theme__switch").addClass("active");
$("body").addClass("dark__theme");
}
});
So when I refresh the page with dark theme on, it waits for the document to be fully loaded, and then adds the class so I get a flicker of white (original bg).
I've tried a couple solutions such as blocking the page rendering by placing a small <script>
tag inside the <head>
:
<script>
// Render blocking JS:
if ($.cookie('toggle') === 'true') document.documentElement.setAttribute("class", dark__theme);
</script>
This solutions almost works, it prevents the flicker of white, but when I change back to light theme, theres a very slight border of the dark__theme
colour around the document, and if you scroll past the top or bottom of the page, its dark__theme
colour and not white, so I think that would be strange for users to see.
This solution also requires me to load the jquery and jquery-cookie library inside of the <head>
which I wasnt too happy about, but if theres a way for this approach to work I'd be okay with it since its a rather small project.
I've also tried creating an overlay:
<div id="overlay"></div>
#overlay {
position: fixed;
top: 0;
right: 0;
left: 0;
bottom: 0;
background: #fff;
}
and then adding this to my original jQuery(document).ready(function ($) {
jQuery('#overlay').hide();
but this solution just does not work for me.
Does anyone have any clever solutions for this problem, or should start over and find a new approach for saving the dark theme?
Thanks for looking!
Upvotes: 0
Views: 88
Reputation: 15857
Since cookies are accessible by both client and server side languages, you could do something like this.
You access the cookie using your SERVER side language and change the body's class on the server side based on the cookie selected.
By doing this, by the time the HTML reaches the browser, the body's class will have already been applied.
Upvotes: 1