Sobes.tech
Middle

How to avoid the 'flash of unstyled content' (FOUC) problem?

sobes.tech AI

Answer from AI

To avoid FOUC, you need to ensure that styles are loaded and applied before the content becomes visible.

Main methods:

  • Critical CSS: Extracting and inlining styles necessary for rendering the above-the-fold content. These styles are placed directly in the <head> of the HTML document.

    <head>
      <style>
        /* Critical styles for the first screen */
        body { margin: 0; }
        h1 { color: blue; }
        /* ... */
      </style>
      <link rel="stylesheet" href="path/to/other/styles.css">
    </head>
    
  • Preloading Stylesheets: Using <link rel="preload"> to tell the browser to start loading critical CSS files as early as possible.

    <head>
      <link rel="preload" href="path/to/critical.css" as="style">
      <link rel="stylesheet" href="path/to/critical.css">
      <link rel="stylesheet" href="path/to/other/styles.css">
    </head>
    

    Note: Use <link rel="stylesheet"> after <link rel="preload"> for actual style application.

  • Asynchronous loading of non-critical styles: Using the media="print" attribute or onload to load non-critical CSS files after the initial rendering.

    <link rel="stylesheet" href="path/to/non-critical.css" media="print" onload="this.media='all'">
    
  • Deferred content rendering: In some cases, you can delay the display of content until styles are ready, using JavaScript. However, this method can negatively impact performance and perception.

    // Example (not recommended in most cases)
    document.documentElement.style.display = 'none';
    window.addEventListener('DOMContentLoaded', (event) => {
      // Ensure styles are loaded (using CSSOM API or other checks)
      requestAnimationFrame(() => {
        document.documentElement.style.display = '';
      });
    });
    
  • Using build tools (Bundlers): Tools like Webpack or Parcel can automate the process of generating critical CSS and managing style loading.

The choice of specific methods depends on the complexity of the project and performance requirements. Combining critical CSS with asynchronous loading is the most common and effective approach.