Home  >  Article  >  Web Front-end  >  How to Prevent Flash of Unstyled Content (FOUC) Without JavaScript?

How to Prevent Flash of Unstyled Content (FOUC) Without JavaScript?

DDD
DDDOriginal
2024-11-14 11:51:02124browse

How to Prevent Flash of Unstyled Content (FOUC) Without JavaScript?

Eliminating the Flash of Unstyled Content

The flash of unstyled content (FOUC) refers to the brief moment when a web page appears with its raw HTML elements before the CSS styles are applied. This jarring effect can negatively impact the user experience.

Solution: Using JavaScript

A common solution involves initially hiding elements using CSS and then using JavaScript to unhide them once the page loads. However, this approach can be problematic for users who have JavaScript disabled.

A Better Approach: Hiding the HTML Element

Instead of hiding individual elements, a more effective approach is to hide the entire HTML element using JavaScript. This can be achieved by adding a hidden class to the HTML tag in the section:

<html>
  <head>
    <style type="text/css">
      .hidden { display: none; }
    </style>
    <!-- ... -->
  </head>
  <body>
    <!-- Body Content -->
  </body>
</html>

In the JavaScript code, the addClass() method is used to hide the HTML element before the document is ready:

$('html').addClass('hidden');

Once the page is loaded (or the document is ready), the HTML element is made visible:

$(document).ready(function() {
  $('html').removeClass('hidden');
});

By hiding the HTML element, all its child elements are hidden as well, preventing any FOUC. Note that the addClass() method should be called outside of the .ready() function for this approach to work effectively.

The above is the detailed content of How to Prevent Flash of Unstyled Content (FOUC) Without JavaScript?. 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