Home  >  Article  >  Web Front-end  >  How to Eliminate Flash of Unstyled Content with Graceful Degradation?

How to Eliminate Flash of Unstyled Content with Graceful Degradation?

Susan Sarandon
Susan SarandonOriginal
2024-11-13 05:06:02474browse

How to Eliminate Flash of Unstyled Content with Graceful Degradation?

Eliminating the Flash of Unstyled Content: A Graceful Degradation Approach

The flash of unstyled content (FOUC) occurs when web page elements appear briefly without their intended styles before JavaScript kicks in to apply those styles. To prevent this unsightly effect, we'll explore a solution that degrades gracefully without compromising functionality for users with JavaScript disabled.

Hide Elements with JavaScript, Not CSS

Initially hiding elements with CSS and then revealing them with JavaScript is problematic because users without JavaScript enabled will never see those elements. A better approach is to use JavaScript for both hiding and displaying elements.

jQuery for Hiding and Showing Page Content

Using jQuery, we can hide page content effectively:

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

Optimizing Display with HTML Hiding

However, for large pages, the above code may not prevent FOUC. Therefore, we can hide the HTML element as soon as JavaScript is encountered in the head:

<html>
  <head>
    <style type="text/css">
      .hidden {display:none;}
    </style>
    <script type="text/javascript">
      $('html').addClass('hidden');
      $(window).on('load', function() {
        $('html').removeClass('hidden');
      });  
    </script>
  </head>
  <body>
    <!-- Body Content -->
  </body>
</html>

Note that the jQuery addClass() method is invoked outside the $(window).on('load') callback to hide the HTML element immediately.

This approach ensures graceful degradation by ensuring that page content is hidden initially and displayed once the page is fully loaded, even for users without JavaScript enabled.

The above is the detailed content of How to Eliminate Flash of Unstyled Content with Graceful Degradation?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn