1 min read

Advanced Font Optimization: Preloading Strategies

Fonts are often the hidden bottleneck in "Largest Contentful Paint" (LCP) and "Cumulative Layout Shift" (CLS). By default, a browser only discovers a font file after it has downloaded the HTML and parsed the CSS file that references it.

Preloading tells the browser: "You are going to need this file soon, start downloading it now."

Why Preload?

  1. Eliminate Render Blocking: Fonts are available immediately when the CSS is applied.
  2. Reduce Layout Shifts: Prevents the text from flashing or changing size (FOUT/FOIT) as the font loads.

Method 1: The WordPress Way (functions.php)

This method injects a <link rel="preload"> tag into the <head> of your HTML. It is the safest and easiest method to manage within a theme because you can use PHP functions to get the correct URL.

Add this to your theme's functions.php:

function my_preload_fonts() {
    // Adjust the path to your specific font file
    $font_url = get_stylesheet_directory_uri() . '/fonts/Inter-VariableFont_opsz,wght.woff2';
    ?>
    <link rel="preload" href="<?php echo esc_url( $font_url ); ?>" as="font" type="font/woff2" crossorigin>
    <?php
}
add_action( 'wp_head', 'my_preload_fonts', 1 );

The crossorigin Attribute

Crucial: You must include crossorigin (or crossorigin="anonymous") even if the font is on your own domain. Without it, the browser will double-download the font (once for the preload, once for the CSS), wasting bandwidth.

Method 2: The Server Way (.htaccess)

This method is faster because it sends the preload directive in the HTTP Headers before the browser even starts parsing the HTML. This gives the browser a head start of several milliseconds.

Add this to the top of your .htaccess file (Apache servers):

<IfModule mod_headers.c>
    # Preload the local font via Header (Matches what your PHP function does)
    # Ensure the path matches your actual file location relative to the domain root
    Header add Link "</wp-content/themes/genesis-sample/inc/fonts/Inter-VariableFont_opsz,wght.woff2>; rel=preload; as=font; type=font/woff2; crossorigin"
</IfModule>

Explanation

  • <IfModule mod_headers.c>: Ensures the server supports header modification so the site doesn't crash if the module is missing.
  • Header add Link: Adds a standard HTTP Link header (RFC 5988).
  • rel=preload; as=font: Tells the browser how to treat the resource.
  • </path/to/font>: The brackets < > are required syntax for the Link header URL.

Best Practices

  • Don't Preload Everything: Only preload the fonts used "Above the Fold" (usually the body text and main heading weight). Preloading too many files will clog the bandwidth and delay the initial page load.
  • Match the URL Exactly: The URL in the preload tag must match the URL in your CSS @font-face rule exactly, or the browser will download it twice.