Blog>
Snippets

Subsetting Fonts for Performance

Present a method for subsetting fonts to include only the needed characters and glyphs, reducing file sizes for faster font loading in a Next.js project.
import { useEffect } from 'react';
import FontFaceObserver from 'fontfaceobserver';

// Load and observe the subset font
const useSubsetFont = (fontName, fontPath) => {
  useEffect(() => {
    const font = new FontFaceObserver(fontName);

    font.load().then(() => {
      document.documentElement.classList.add('fonts-loaded');
    }).catch((e) => {
      console.error('Font loading failed:', e);
    });

    const link = document.createElement('link');
    link.href = fontPath;
    link.rel = 'stylesheet';
    link.type = 'text/css';
    document.head.appendChild(link);
  }, [fontName, fontPath]);
};

export default useSubsetFont;
This JavaScript code snippet defines a custom hook `useSubsetFont` which uses the FontFaceObserver library to load a subset of a web font asynchronously for performance. It appends the font stylesheet to the document head and adds a class to the document element once the font is loaded. It takes two parameters: `fontName`, the name of the font, and `fontPath`, the URL of the subset font's stylesheet. This hook can be used inside any component in a Next.js project.