Eliminate flash of unstyled content

前端 未结 12 2042
一个人的身影
一个人的身影 2020-11-28 02:39

How do I stop the flash of unstyled content (FOUC) on a web page?

12条回答
  •  我在风中等你
    2020-11-28 03:18

    The problem with using a css style to initially hide some page elements, and then using javascript to change the style back to visible after page load, is that people who don't have javascript enabled will never get to see those elements. So it's a solution which does not degrade gracefully.

    A better way therefore, is to use javascript to both initially hide as well as redisplay those elements after page load. Using jQuery, we might be tempted to do something like this:

    $(document).ready(function() {
        $('body').hide();
        $(window).on('load', function() {
            $('body').show();
        });
    });
    

    However, if your page is very big with a lot of elements, then this code won't be applied soon enough (the document body won't be ready soon enough) and you might still see a FOUC. However, there is one element that we CAN hide as soon as script is encountered in the head, even before the document is ready: the HTML tag. So we could do something like this:

    
      
      
      
      
      
       
       
       
       
    
    

    Note that the jQuery addClass() method is called *outside* of the .ready() (or better, .on('load')) method.

提交回复
热议问题