Blog>
Snippets

Using Font Display Swap to Enhance Text Visibility

Showcase the implementation of `font-display: swap;` in CSS to ensure text remains visible during webfont load, reducing Cumulative Layout Shift (CLS) and enhancing user experience.
const styleSheet = document.createElement('style');
styleSheet.type = 'text/css';
styleSheet.textContent = `
@font-face {
  font-family: 'MyWebFont';
  src: url('/path-to-webfont.woff2') format('woff2'),
       url('/path-to-webfont.woff') format('woff');
  font-display: swap; /* This is where font-display is set to swap */
}
body {
  font-family: 'MyWebFont', sans-serif;
}`;
document.head.appendChild(styleSheet);
This JavaScript code creates a new style element, sets its type to 'text/css', and appends it to the head of the document. Within the style element, it defines a `@font-face` rule that specifies the font family name 'MyWebFont' and its source files, along with the 'font-display' property set to 'swap'. It ensures that if 'MyWebFont' is not available, text is initially displayed with a fallback font to avoid invisible text during loading ('flash of invisible text' or FOIT), then swaps to 'MyWebFont' when it loads. This reduces CLS and improves the user experience.