0
0
Astroframework~5 mins

Font optimization in Astro

Choose your learning style9 modes available
Introduction

Font optimization helps your website load faster and look better by using only the fonts you need.

When you want your website to load quickly on slow internet.
When you want to reduce the size of font files sent to the browser.
When you want to improve user experience by avoiding invisible or jumping text.
When you want to use custom fonts without slowing down your site.
When you want to improve your website's performance scores.
Syntax
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).

Examples
This example loads the Roboto font with preload and swap display for better performance.
Astro
import { font } from 'astro:font';

const roboto = font({
  src: './fonts/Roboto-Regular.woff2',
  preload: true,
  display: 'swap'
});
This example loads Open Sans bold italic font with Latin and Cyrillic characters.
Astro
import { font } from 'astro:font';

const openSans = font({
  src: './fonts/OpenSans-Bold.woff2',
  weight: '700',
  style: 'italic',
  subsets: ['latin', 'cyrillic']
});
Sample Program

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.

Astro
---
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>
OutputSuccess
Important Notes

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.

Summary

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.