Performance PHP Beginner

Preload Your Main Web Font

Tell the browser to download your main self-hosted font file early, so text appears in the right font sooner.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 9 lines
add_action( 'wp_head', function (): void {
	// Path to your font inside the active theme. Use the woff2 file your CSS actually loads.
	$font = get_theme_file_uri( 'assets/fonts/inter-variable.woff2' );

	printf(
		'<link rel="preload" href="%s" as="font" type="font/woff2" crossorigin>' . "\n",
		esc_url( $font )
	);
}, 1 );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

Browsers only discover a font after downloading and reading the CSS that uses it, so text can appear in a fallback font first and then jump. Preloading your main font starts the download immediately.

How it works

The snippet prints a &lt;link rel="preload" as="font"&gt; tag at the very top of the head. get_theme_file_uri() builds the URL inside your active theme, or the parent theme if a child theme doesn’t have the file.

Fonts are always fetched in CORS mode, so the crossorigin attribute is required, even for fonts on your own domain. Without it the browser downloads the font twice.

Things to watch

  • Only preload one or two fonts, the ones used for body text and headings above the fold. Preloading everything competes with more important files.
  • The URL must match the one in your CSS exactly, including any version query string, or the preload is wasted.
  • Nahnu Fonts and some themes add preloads for you. Check your page source first.

How to test it

Open DevTools → Network, filter by Font and reload. Your font should be one of the first requests, with no duplicate download.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only