I am currently working on implementing a theme toggle with local storage using JavaScript.
The issue I am facing is that when switching from a dark theme to a light theme and then navigating to a new page, the background blinks black briefly because the base theme's body background color is set to black. I have attempted to remove both backgrounds and handle them in JavaScript, but still encounter a blink effect either with the black or white background when transitioning between themes.
My theme toggle switches my site between dark and white modes. However, upon refreshing the page or navigating to a new one while in white mode, there is a quick flickering of the body's inherited black background color from the default dark theme before settling on the white theme. My goal is to achieve a seamless transition between themes and pages without any blinking of the background in black or white based on the respective theme colors.
Below is my current code:
function checkBG() {
//REDUCE FLICKER ON PAGE CHANGE
if(lightmodeON = true) {
console.log('loading white bg');
}
if(lightmodeON = false) {
console.log('loading black bg');
}
if(window.matchMedia('(prefers-color-scheme: dark)').matches && localStorage.themepref == 2 ) {
darkmode();
console.log("OS Setting DARK MODE");
}
if (window.matchMedia("(prefers-color-scheme: light)").matches && localStorage.themepref == 1 ) {
lightmode();
console.log("OS Setting LIGHT MODE");
}
if(window.matchMedia('(prefers-color-scheme: dark)').matches && localStorage.themepref == "undefined" ) {
darkmode();
console.log("OS Setting DARK MODE");
}
if (window.matchMedia("(prefers-color-scheme: light)").matches && localStorage.themepref == "undefined" ) {
lightmode();
console.log("OS Setting LIGHT MODE");
}
};
$(window).ready(function($) {
checkBG();
$(window).scrollTop( $("#top").offset().top );
$(document).scrollTop(0);
if (typeof (Storage) !=="undefined") {
if (localStorage.themepref == 1 ) {
lightmode();
}
else {
darkmode();
localStorage.themepref = 2;
}
}
In the light mode and dark mode functions, I define the body background color.
Despite this, there seems to be a delay in updating the DOM or browser rendering, causing a black blink on every page refresh or click when switching to the white theme due to the initial black theme setting. Any suggestions for a proper workaround to address this issue would be greatly appreciated.
Thank you.