I have a switcher that is changing backgrounds and setting a cookie using the jquery cookie script. It looks something like:
$(document).ready(function(){
var colors = $.cookie('colors');
$(".box_2f2").click(function(){
$('body').removeClass('c000 cfff c2f2');
$('body').addClass('c2f2');
$.cookie('colors','middleGrey');
return false;
});
$(".box_fff").click(function(){
$('body').removeClass('c000 cfff c2f2');
$('body').addClass('cfff');
$.cookie('colors','white');
return false;
});
$(".box_000").click(function(){
$('body').removeClass('c000 cfff c2f2');
$('body').addClass('c000');
$.cookie('colors','black');
return false;
});
if(colors == 'middleGrey')
{
$('body').addClass('c2f2');
}
if (colors == 'white')
{
$('body').addClass('cfff');
}
if(colors == 'black')
{
$('body').addClass('c000');
}
});
the problem with this is because the class isnt set until that piece of javascript is loaded or the content is cached, the page will blink the defualt white background before showing the cookied style. What is a better way to code this so the class is applied earlier in the dom and does not have to wait for all of the scripts?
By using jQuery, you’re dependent on the scripts to be either loaded from the cache or the web server. Unfortunately you’ll have that bit of a flash while everything gets loaded.
ALTERNATIVELY, however, you could have something like the following applied just after opening the BODY tag of your page using NORMAL JavaScript (without being dependent on a library or framework):
…then just set the “display” CSS property of the body back to “block” or whatever your preference is at the very end of your jQuery script there.