Menü schliessen
Created: February 5th 2024
Last updated: March 16th 2024
Categories: Common Web Development,  Php,  Wordpress
Author: Tim Fürer

WordPress: How to preload fonts

Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

In today's digital landscape, user experience is paramount. Every aspect of a website, from its design to its functionality, plays a crucial role in engaging visitors and keeping them hooked. One often overlooked element that significantly impacts user experience is font loading speed. Slow-loading fonts can lead to frustrating delays and hinder the overall performance of a website.


Helper Function

<?php

function preload_fonts() {
    $fonts = [
        'fonts/foo.ttf' => 'ttf',
        'fonts/bar.otf' => 'otf',
        'fonts/fizz.woff' => 'woff',
        'fonts/buzz.woff2' => 'woff2',
    ];

    foreach ($fonts as $font => $type) {
        ?>

        <link rel="preload" href="<?= esc_attr(trailingslashit(get_stylesheet_directory_uri()) . $font) ?>" as="font" type="font/<?= esc_attr($type) ?>" crossorigin />

        <?php
    }
}
add_action('wp_head', 'preload_fonts');

?>

How It Works

  1. Font Definition: The $fonts array contains the paths to the font files and their corresponding types (e.g., TrueType Font, OpenType Font, WOFF, WOFF2).
  2. Iteration: The foreach loop iterates through each font defined in the $fonts array.
  3. Link Preloading: Within the loop, a <link> tag is dynamically generated for each font file. The rel="preload" attribute instructs the browser to fetch and cache the font files preemptively, before they are actually needed. This preemptive fetching significantly reduces the latency associated with font loading.
  4. Cross-Origin Resource Sharing (CORS): The crossorigin attribute ensures that the fonts can be loaded securely across different domains, if necessary.
  5. Hooking into wp_head: The preload_fonts() function is hooked into the wp_head action, ensuring that the font preloading occurs within the <head> section of the HTML document.

Benefits

  • Improved Performance: Preloading fonts reduces latency by fetching resources preemptively, leading to faster page load times.
  • Enhanced User Experience: With quicker font loading, visitors experience smoother and more seamless browsing sessions.
  • Optimized SEO: Faster page load times contribute positively to search engine rankings, improving overall visibility and discoverability.