Performance: Font optimization
Font optimization affects page load speed and visual stability by controlling how fonts are loaded and rendered.
--- // Preload key font in head const preloadFont = () => { return `<link rel="preload" href="/fonts/myfont.woff2" as="font" type="font/woff2" crossorigin="anonymous" />`; }; --- <head> {Astro.raw(preloadFont())} <style> @font-face { font-family: 'MyFont'; src: url('/fonts/myfont.woff2') format('woff2'); font-display: swap; font-weight: 400; font-style: normal; } </style> </head>
import './styles.css'; /* styles.css includes @font-face with multiple font weights and styles, no preload or font-display set */
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Load all fonts without preload or font-display | Minimal | Multiple reflows due to late font swap | High paint cost from layout shifts | [X] Bad |
| Preload key fonts and use font-display: swap | Minimal | Single reflow or none | Low paint cost with stable layout | [OK] Good |
Font helper to preload a font with display swap?import { Font } from '@astrojs/font'; const myFont = Font({ src: '/fonts/myfont.woff2', display: 'swap', preload: true }); correctly uses preload: true and display: 'swap' which matches best practices.import { Font } from '@astrojs/font'; const myFont = Font({ src: '/fonts/myfont.woff2', display: 'swap', preload: true }); [OK]import { Font } from '@astrojs/font';
const roboto = Font({ src: '/fonts/roboto.woff2', display: 'swap', preload: true });
export default function Page() {
return <h1 style={{ fontFamily: roboto.style }}>Hello</h1>;
}import { Font } from '@astrojs/font';
const openSans = Font({ src: '/fonts/opensans.woff2', display: 'fallback', preload: 'yes' });import { Font } from '@astrojs/font';
const headingFont = Font({ src: '/fonts/heading.woff2', display: 'swap', preload: true });
const bodyFont = Font({ src: '/fonts/body.woff2', display: 'swap', preload: false }); sets preload: true and display: 'swap' correctly.import { Font } from '@astrojs/font';
const headingFont = Font({ src: '/fonts/heading.woff2', display: 'swap', preload: true });
const bodyFont = Font({ src: '/fonts/body.woff2', display: 'swap', preload: false });.import { Font } from '@astrojs/font';
const headingFont = Font({ src: '/fonts/heading.woff2', display: 'swap', preload: true });
const bodyFont = Font({ src: '/fonts/body.woff2', display: 'swap', preload: false }); -> Option Cimport { Font } from '@astrojs/font';
const headingFont = Font({ src: '/fonts/heading.woff2', display: 'swap', preload: true });
const bodyFont = Font({ src: '/fonts/body.woff2', display: 'swap', preload: false }); [OK]Pass the test and this pattern moves unknown