Site icon Hip-Hop Website Design and Development

What’s the most efficient way to preload multiple font types using links and enqueue?

I added some code to my theme to preload my self-hosted enqueued fonts that are coming in via @font-face. I then added a filter to set the attributes. Seems to work and the pages load a bit faster too.

I’m not sure how to handle the various font types—eot ttf woff woff2—in the most efficient way so the browser doesn’t load them all for no reason, and to keep the code as minimal as possible. Not sure if there is a short-hand way for this or if everything needs to be enqueued and filtered one by one.

I also would like to know if I should be using wp_register_style and then use wp_enqueue_style for the preload, or if it’s fine to simply enqueue the fonts for the preload without registering.

Enqueued Fonts

wp_enqueue_style('font-1', get_stylesheet_directory_uri() . 'library/fonts/font-1.woff2', array(), null);
wp_enqueue_style('font-2', get_stylesheet_directory_uri() . 'library/fonts/font-2.woff2', array(), null);
wp_enqueue_style('font-3', get_stylesheet_directory_uri() . 'library/fonts/font-3.woff2', array(), null);

Filter

add_filter('style_loader_tag', 'my_font_style_filter', 10, 2);
function my_font_style_filter($html, $handle) {
    if ($handle === 'font-1' || $handle === 'font-2' || $handle === 'font-3') {
        return str_replace("rel='stylesheet'", "rel='preload' as='font' type='font/woff2' crossorigin='anonymous'", $html);
    }
    return $html;
}