Sobes.tech
Middle

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

sobes.tech AI

Answer from AI

Most effective methods:

  1. Synchronous CSS loading: Place <link rel="stylesheet"> in the <head> of the document so that the browser loads and applies styles before rendering content.

    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>My App</title>
      <link rel="stylesheet" href="/styles/main.css">
      <!-- Other head tags -->
    </head>
    
  2. Inlining critical styles: Inline styles necessary for displaying the visible part of the page ("Above the fold") directly in <head> using the <style> tag. This speeds up initial rendering. Other styles can be loaded asynchronously.

    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>My App</title>
      <style>
        /* Critical styles here */
        body { margin: 0; padding: 0; }
        h1 { color: blue; }
      </style>
      <link rel="stylesheet" href="/styles/main.css">
      <!-- Other head tags -->
    </head>
    
  3. Using font-display: swap or similar properties for fonts: For custom fonts that may cause FOUT (Flash of Unstyled Text), use font-display in the @font-face CSS rule. swap allows the text to be displayed immediately with a system font and replaced with the custom font after loading.

    @font-face {
      font-family: 'MyCustomFont';
      src: url('my-custom-font.woff2') format('woff2');
      font-display: swap; /* Or fallback, optional, block */
    }
    
  4. Applying lightweight templates (in server-side rendering): If server-side rendering (SSR) is used, embed a minimal set of styles necessary for displaying the page skeleton into the HTML.

  5. Minimizing and combining CSS files: Reducing the number of HTTP requests and the size of CSS files speeds up their loading.

  6. Using build tools: Webpack, Parcel, and other bundlers can automate critical style inlining and CSS optimization.