How to avoid the problem of 'flash of unstyled content' (FOUC)?
sobes.tech AI
Answer from AI
Most effective methods:
-
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> -
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> -
Using
font-display: swapor similar properties for fonts: For custom fonts that may cause FOUT (Flash of Unstyled Text), usefont-displayin the@font-faceCSS rule.swapallows 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 */ } -
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.
-
Minimizing and combining CSS files: Reducing the number of HTTP requests and the size of CSS files speeds up their loading.
-
Using build tools: Webpack, Parcel, and other bundlers can automate critical style inlining and CSS optimization.