Vite

Preloading self-hosted WOFF2 fonts in Vite

Serve WOFF2 fonts locally, control rendering with font-display, and use a Vite build hook to preload the emitted hashed font files.

Preloading self-hosted WOFF2 fonts in Vite

A browser often learns it needs a web font after it has downloaded and parsed CSS. I used local WOFF2 files, font-display, and an HTML preload generated at build time to move the critical request earlier.

Why an external font can delay text

An external font service can introduce extra DNS lookups and TLS handshakes. The browser discovers a stylesheet, parses its font declarations, and requests a font when the rendered text needs that face. Each step can move discovery later. While waiting, a browser may hide the text briefly or draw a fallback and swap the font later.

A swap can still move glyphs and change line breaks if the fonts have different metrics. Self-hosting removes separate font origins from the path. It also makes font versions and caching behavior part of the application’s deployment.

Moving discovery to the HTML

A font preload lets the browser start fetching the asset before CSS completes. It helps most when the preloaded font is used in the initial viewport. Preloading every weight competes with other critical resources and can waste the bandwidth it was meant to save.

sequenceDiagram
    participant B as Browser
    participant H as HTML
    participant C as CSS
    participant F as WOFF2 font
    B->>H: Request page
    H-->>B: HTML and preload link
    par Early font request
        B->>F: Preload chosen face
    and Stylesheet request
        B->>C: Download and parse CSS
    end
    B->>B: Use the preloaded response when the face matches

I keep the needed WOFF2 faces as source assets and reserve additional weights for CSS to discover normally. Use @font-face to register the filenames and font-display: swap to let the browser draw fallback text while it waits. Use a subset only when it covers the scripts and characters the site actually needs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/* src/styles/fonts.css */
@font-face {
  font-family: 'Pretendard';
  font-style: normal;
  font-weight: 400;
  font-display: swap;
  src: url('../assets/fonts/Pretendard-Regular.woff2') format('woff2');
}

@font-face {
  font-family: 'Pretendard';
  font-style: normal;
  font-weight: 700;
  font-display: swap;
  src: url('../assets/fonts/Pretendard-Bold.woff2') format('woff2');
}

body {
  font-family: 'Pretendard', -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
}

Resolving the emitted filename at build time

Source names can change when Vite emits assets with content hashes. Hardcoding a built URL in index.html makes the preload go stale. This example runs the HTML transform after build asset information is available. It looks through emitted WOFF2 assets and adds preload links for the selected Pretendard faces.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// plugins/vitePluginFontPreload.ts
import { Plugin } from 'vite';

export function fontPreloadPlugin(): Plugin {
  return {
    name: 'vite-plugin-font-preload',
    enforce: 'post',
    transformIndexHtml(html, ctx) {
      if (!ctx.bundle) return html;

      const fontPreloadTags: string[] = [];

      // Find WOFF2 font assets in the output bundle.
      for (const [fileName, file] of Object.entries(ctx.bundle)) {
        if (file.type === 'asset' && fileName.endsWith('.woff2')) {
          // Generate preloads only for the selected Pretendard faces.
          if (fileName.includes('Pretendard')) {
            fontPreloadTags.push(
              `<link rel="preload" href="/${fileName}" as="font" type="font/woff2" crossorigin>`
            );
          }
        }
      }

      // Insert preload tags just before the closing head tag.
      return html.replace('</head>', `  ${fontPreloadTags.join('\n  ')}\n</head>`);
    }
  };
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// vite.config.ts
import { defineConfig } from 'vite';
import { fontPreloadPlugin } from './plugins/vitePluginFontPreload';

export default defineConfig({
  plugins: [
    fontPreloadPlugin()
  ],
  build: {
    rollupOptions: {
      output: {
        assetFileNames: (assetInfo) => {
          // Write hashed font assets under dist/assets.
          if (assetInfo.name && assetInfo.name.endsWith('.woff2')) {
            return 'assets/[name]-[hash][extname]';
          }
          return 'assets/[name]-[hash][extname]';
        }
      }
    }
  }
});

Set crossorigin on a font preload, including for same-origin fonts, so the preload’s request mode matches CSS. Verify that the final CSS URL and the preload URL are identical. A mismatch can create a second request.

The sample assumes a root deployment for its emitted paths. If the application is hosted below a path prefix or uses a separate CDN, account for Vite’s public base in the preload href and repeat the browser check at that deployment path.

Verifying the HTML, headers, and waterfall

Run pnpm vite build. Inspect dist/index.html for the as="font" and type="font/woff2" tags and confirm they point to files the build actually emitted.

Hashed WOFF2 assets and generated preload tags in the Vite build Figure 1. The build emits hashed Regular and Bold fonts and adds matching links to the HTML.

Run vite preview or serve the output behind your intended host. Use curl -I on the font URL and inspect the linked stylesheet for font-display. Configure long-lived immutable caching for hashed assets on the production host. Preview-server headers do not establish a production caching policy.

Font request response headers and font-display rule in the preview Figure 2. Check the served font headers and the generated CSS declaration.

Reading the performance result

CheckExternal-font versionLocal and preloaded version
Origins in this exampleApplication and two font-related originsApplication origin
Font discoveryAfter the stylesheet and rendered textFrom the initial HTML for selected faces
Text renderingCould wait for a font downloadFallback can render before the custom font
LCP in the recorded comparisonAbout 1.4 secondsAbout 0.6 seconds

The comparison describes this page and measurement setup. It is not a general LCP target. Record cold-cache runs with the same viewport and network profile. Check if the same LCP element wins in both runs, whether the font was only requested once, and whether swapping still shifts text.

This post is licensed under CC BY 4.0 by the author.