If you're going to be deferring more than one stylesheet, I've found this approach to be fairly reusable.
- Put this somewhere:
function _changeme_defer_css( $html, $handle ) {
$deferred_stylesheets = apply_filters( 'changeme_deferred_stylesheets', array() );
if ( in_array( $handle, $deferred_stylesheets, true ) ) {
return str_replace( 'media=\'all\'', 'media="print" onload="this.media=\'all\'"', $html );
} else {
return $html;
}
}
add_filter( 'style_loader_tag', '_changeme_defer_css', 10, 2 );
- Load your font as you normally would:
function _changeme_load_font_awesome() {
wp_enqueue_style( 'font-awesome', URI . '/fonts/font-awesome/css/font-awesome.min.css' );
}
add_filter( 'wp_enqueue_scripts', '_changeme_load_font_awesome' );
- Defer it like so:
add_filter( 'changeme_deferred_stylesheets', function( $handles ) {
$handles[] = 'font-awesome';
return $handles;
}, 10, 1 );
- If you want to make sure it only impacts the public-facing side of your site, and not
wp-admin
, you could add a check for ! is_admin()
as well (especially for commonly-used libraries like Font Awesome
or Select2
):
add_filter( 'changeme_deferred_stylesheets', function( $handles ) {
if ( ! is_admin() ) {
$handles[] = 'font-awesome';
}
return $handles;
}, 10, 1 );
I also updated the onload
approach based on Scott Jehl's The Simplest Way to Load CSS Asynchronously (2019) but if you're going to do this, you may also want to read the "Async CSS" passage from Harry Roberts's The Fastest Google Fonts (2020) to see why he recommends preloading as well.