Optimising Google Fonts in WordPress

Harry Roberts has a great piece on optisiming Goolge Fonts. I’m going to assume you’ve read it, and show you how you might implement his suggestions in WordPress.

Firstly, WordPress automatically adds dns-prefetch for any styles or scripts from external hosts. Harry doesn’t mention dns-prefetch at all, so lets just mark that down as a good-to-know and move swiftly on.

I’m not going to bother with running the numbers here as Harry has already kindly done that for us. So without further ado…

Async CSS

This is a very nice little trick. It’s certainly worth reading the Filament Group post about it. To do this in WordPress, the style_loader_tag hook can be used:

<?php

add_filter( 'style_loader_tag', 'google_fonts_async', 10, 3 );
/**
 * Load Google Fonts Asynchrously
 * 
 * @see https://www.filamentgroup.com/lab/load-css-simpler/
 */
function google_fonts_async( $html, $handle, $href ) {
    if ( false === strpos( $href, 'fonts.googleapis.com/css' ) ) {
        return $html;
    }

    return str_replace(
        "media='all'",
        "media='print' onload=\"this.media='all'\"",
        $html
    );
}

I’m checking the href here, so any styles with ‘fonts.googleapis.com/css’ will be loaded asychronously, but you could just use the handle if you want to target a specific stylesheet.

Also, some plugins remove media='all' from link tags. In that case rel='stylesheet' can be used for the string replacement.

preload

WordPress does not have an API for preloading links yet, so we can just use wp_head for the time being.

<?php

add_action( 'wp_head', 'google_fonts_preload', 1 );
/**
 * Add preload link for Google Fonts
 */
function google_fonts_preload() {
    ?>

    <link rel='preload' as='style' href='GOOGLE-FONTS-URL'>

    <?php
}

Alex MacArthur has a post on automating the preloading of scripts.

preconnect

This one was used in the Twenty Seventeen theme, which was probably released around the same time as WordPress 4.6 when wp_resource_hints() was introduced.

<?php

add_filter( 'wp_resource_hints', 'google_fonts_resource_hints', 10, 2 );
/**
 * Add resource hints for Google Fonts
 */
function google_fonts_resource_hints( $urls, $relation_type ) {
	if ( 'preconnect' === $relation_type ) {
		$urls[] = [
			'href' => 'https://fonts.gstatic.com',
			'crossorigin'
		];
	}

	return $urls;
}

Plugin

I’ve created a little plugin with all of the above. Here’s the gist. Drop it into your mu-plugins directory then in your theme:

<?php

if ( class_exists( 'ylkyrg\OptimiseGoogleFonts' ) ) {
	( new ylkyrg\OptimiseGoogleFonts() )->run();
}

It can take an array with either the handle or href for the fonts.

<?php

if ( class_exists( 'ylkyrg\OptimiseGoogleFonts' ) ) {
	( new ylkyrg\OptimiseGoogleFonts(
		[
			'handle' => 'google-fonts-handle',
			'href'   => 'GOOGLE-FONTS-URL'
		]
	) )->run();
}

If the handle is provided only that specific style is targeted. The href is requied to add preloading.