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);


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;
  • They way that I do it is to convert the font into a data:uri in css and preload the stylesheet. -Brian Nov 27 '21 at 4:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.