Dynamic Font Loading with Next.js 14
Demonstrate how to dynamically load fonts using the `next/head` component and local font files in a Next.js application to reduce unnecessary font loading and improve performance.
import Head from 'next/head';
export default function Home() {
return (
<div>
<Head>
{/* Dynamic font loading for local font files */}
<link
rel="preload"
href="/fonts/custom-font.woff2"
as="font"
type="font/woff2"
crossOrigin="anonymous"
/>
<style>
{`
@font-face {
font-family: 'CustomFont';
src: url('/fonts/custom-font.woff2') format('woff2');
font-weight: 400;
font-style: normal;
font-display: swap;
}
`}
</style>
</Head>
{/* Rest of the component */}
</div>
);
}
In the Next.js component, we import the Head component and use it to dynamically load our local font file. Preloading the font as a resource indicates to the browser that this font file is important and should be loaded early on. We also define a custom `@font-face` in inline styles, specifying the font family name to be used in CSS, the path to the font file, and a `font-display` property with the value 'swap' to ensure text remains visible during font loading.