Home  >  Article  >  Web Front-end  >  How to Eliminate Flash of Unstyled Content (FOUC) in a More Effective Way?

How to Eliminate Flash of Unstyled Content (FOUC) in a More Effective Way?

Linda Hamilton
Linda HamiltonOriginal
2024-11-13 17:33:02199browse

How to Eliminate Flash of Unstyled Content (FOUC) in a More Effective Way?

Eliminating Flash of Unstyled Content

The flash of unstyled content (FOUC) occurs when a web page briefly appears unstyled before the browser can apply the CSS stylesheet. This article explores a more effective approach to prevent FOUC, using JavaScript to initially hide and then unhide page elements:

Hiding and Unhiding with JavaScript

Initially hiding page elements with CSS and then unhiding them with JavaScript can lead to accessibility issues for users with JavaScript disabled. A better solution is to use JavaScript for both hiding and unhiding.

Example with jQuery

One possible approach using jQuery:

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

However, this method relies on the document body being ready before hiding it, which may still lead to some FOUC.

Optimized Approach: Hiding the HTML Tag

An alternative strategy is to use JavaScript to hide the HTML tag immediately when script is encountered in the head, even before the document is ready:

<html>
  <head>
    <!-- Other stuff like title and meta tags go here -->
    <style type="text/css">
      .hidden {display:none;}
    </style>
    <script type="text/javascript" src="/scripts/jquery.js"></script>
    <script type="text/javascript">
      $('html').addClass('hidden');
      $(window).on('load', function () {
        $('html').show();
      });  
    </script>
  </head>
  <body>
    <!-- Body Content -->
  </body>
</html>

In this example, the jQuery addClass() method is called outside of the .load() function to hide the HTML tag immediately.

The above is the detailed content of How to Eliminate Flash of Unstyled Content (FOUC) in a More Effective Way?. 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