Implementing System Fonts as a Fallback
Provide a CSS example setting system fonts as a fallback while custom fonts are loading, improving perceived performance by immediately displaying text with a default font.
const styleSheet = document.createElement('style');
styleSheet.type = 'text/css';
styleSheet.innerText = `
@font-face {
font-family: 'CustomFont';
src: url('path-to-your-font.woff2') format('woff2');
font-display: swap; /* Use system font until custom font is loaded */
}
body {
font-family: 'CustomFont', system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}
`;
document.head.appendChild(styleSheet);
Creates a style element, sets its content to include an @font-face rule with font-display: swap; which will use system fonts as a fallback until the custom font is loaded. Then it appends this style element to the head of the document.