Maison  >  Article  >  interface Web  >  Comment éliminer le Flash de contenu non stylé (FOUC) de manière plus efficace ?

Comment éliminer le Flash de contenu non stylé (FOUC) de manière plus efficace ?

Linda Hamilton
Linda Hamiltonoriginal
2024-11-13 17:33:02199parcourir

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.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn