简体   繁体   中英

Best way to define a class with a cookie

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):

<script type="text/javascript">
    document.body.style["display"] = "none";
</script>

...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.

This is the common flash-of-unstyled-markup problem.

You can frame the entire page in a div, mark it "display:none" or "visibility:collapse" at first, then display it at the end of your script. The page will be just the default browser background until your script completes, which may take some time.

Consider having a "loading" graphic or splash screen before your script runs (if it takes more than 100-200ms), so that the user will know that something is happening and should wait a bit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM