Preloading Fonts

Preloading fonts is a technique used to load fonts before they're required, which can improve your website's performance. However, it's essential to preload only critical fonts to avoid unnecessarily increasing initial load times.

Warning: Preloading can have negative effects on Core Web Vitals if not used correctly. Only preload fonts that are critical for the initial page display.

Preloading in Next.js

To preload a font in Next.js, you need to import the font file URL and add a link tag in your layout:

// app/layout.tsx
import '@typewe/inter/css/index.css';
import interWoff2 from '@typewe/inter/fonts/Inter-Variable.woff2?url';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <head>
        <link
          rel="preload"
          as="font"
          type="font/woff2"
          href={interWoff2}
          crossOrigin="anonymous"
        />
      </head>
      <body>{children}</body>
    </html>
  );
}

Note: The ?url suffix is a Vite/Webpack directive that imports the file path rather than the file contents.

Preloading in Vite/React

For Vite projects, you can use the same approach in your index.html:

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <!-- Preload critical font -->
    <link
      rel="preload"
      as="font"
      type="font/woff2"
      href="/node_modules/@typewe/inter/fonts/Inter-Variable.woff2"
      crossorigin="anonymous"
    />

    <title>My App</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>

Best Practices

1.

Only Preload Critical Fonts

Only preload fonts that are essential for the initial page display. Preloading too many fonts can slow down your page.

2.

Use crossorigin="anonymous"

Always include crossorigin="anonymous" to ensure fonts are loaded correctly with CORS.

3.

Monitor Core Web Vitals

Use tools like Lighthouse or WebPageTest to ensure preloading actually improves performance and doesn't negatively impact Core Web Vitals.

4.

Consider Variable Fonts

Variable fonts are ideal for preloading since a single file contains all weights, reducing the number of files you need to preload.

Learn more: Read the Web.dev article on preloading for more information.