How to load CSS asynchronously in WordPress [Snippet]

It is a common workaround to do change in WordPress how some CSS assets are loaded in the HTML file.

Basically this HTML tricks let the browser to preload the CSS assets, and when it’s done load it as stylesheet so they take a lot of priority in the page.

add_filter('style_loader_tag', 'preload_gfont', 10, 2);

function preload_gfont($html, $handle) {
  if ( $handle === 'google-fonts' || strpos( $handle, 'fontawesome' ) !== false ) {
    return str_replace("rel='stylesheet'",
               "rel='preload' as='style' onload=\"this.rel='stylesheet'\"", $html);

  return $html;

We can see that in this case we are adding this trick for Google Fonts and Fontawesome.

I suggest also to switch from Google Font to Bunny Fonts, this is an example how you can switch to this new CDN that is better for GDPR and compatible at 100% with the same URL:

wp_enqueue_style( 'google-fonts', ',700&display=swap', array(), $css_version );


Liked it? Take a second to support Mte90 on Patreon!
Become a patron at Patreon!

Leave a Reply

Your email address will not be published. Required fields are marked *