Blog>
Snippets

Preloading Critical Fonts to Prioritize Loading

Explain how to use `<link rel='preload'>` to instruct the browser to load essential fonts earlier in the page load process, reducing time to text paint in Next.js applications.
import Head from 'next/head';

export default function MyDocument() {
  return (
    <Head>
      {/* Preload custom fonts */}
      <link
        rel='preload'
        href='/fonts/my-custom-font.woff2'
        as='font'
        type='font/woff2'
        crossOrigin='anonymous'
      />
      <link
        rel='preload'
        href='/fonts/another-custom-font.woff2'
        as='font'
        type='font/woff2'
        crossOrigin='anonymous'
      />
     </Head>
  );
}
This code snippet should be included inside a custom _document.js file in Next.js. It uses the `<Head>` component from Next.js to insert `<link rel='preload'>` tags within the head of the document. Each link tag specifies the `rel='preload'` attribute, indicating to the browser that it should prioritarily load the specified resource, in this case, custom font files. The `as='font'` attribute specifies the type of content being preloaded, and `crossOrigin='anonymous'` is used for proper CORS handling. The `type` attribute specifies the font file type. Include the actual path to your font files in the `href` attribute.