Font optimization helps your website load faster and look better by using only the fonts you need.
Font optimization in Astro
import { font } from 'astro:font'; const myFont = font({ src: './fonts/MyFont.woff2', preload: true, display: 'swap', subsets: ['latin'], weight: '400', style: 'normal' });
preload: Loads the font early for faster display.
display: Controls how text is shown while font loads (e.g., 'swap' shows fallback text first).
import { font } from 'astro:font'; const roboto = font({ src: './fonts/Roboto-Regular.woff2', preload: true, display: 'swap' });
import { font } from 'astro:font'; const openSans = font({ src: './fonts/OpenSans-Bold.woff2', weight: '700', style: 'italic', subsets: ['latin', 'cyrillic'] });
This Astro component imports and optimizes the Lato font. It preloads the font and uses the 'swap' display to show fallback text while loading. The font style is injected into the head, and the body uses the Lato font family.
--- import { font } from 'astro:font'; const lato = font({ src: './fonts/Lato-Regular.woff2', preload: true, display: 'swap', subsets: ['latin'], weight: '400', style: 'normal' }); --- <html lang="en"> <head> <title>Font Optimization Example</title> <link rel="preload" href={lato.url} as="font" type="font/woff2" crossorigin /> {lato.style} </head> <body style="font-family: 'Lato', sans-serif;"> <h1>Hello, this text uses the optimized Lato font!</h1> <p>Font optimization helps this page load faster and look nice.</p> </body> </html>
Always preload fonts you use above the fold to avoid invisible text.
Use font-display: swap to show fallback fonts while your custom font loads.
Limit font subsets and weights to only what you need to reduce file size.
Font optimization makes your website faster and smoother.
Astro's font helper lets you easily load and control fonts.
Preload fonts and use display: 'swap' for best user experience.