[Snippet] How to load CSS asynchronously in WordPress

It is a common workaround to do changes in WordPress, about how some CSS assets are loaded in the HTML file generated.

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.onload=null;this.rel='stylesheet'\"", $html);
  }

  return $html;
}

We can see that in this case we are adding this trick for Google Fonts and Fontawesome.
It’s the case to do it just for some files and not all the CSS otherwise doesn’t make sense the “priority” purpose.

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', 'https://fonts.bunny.net/css?family=Oxygen:400,700&display=swap', array(), $css_version );

 

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

2 thoughts on “[Snippet] How to load CSS asynchronously in WordPress

  1. Thank you for the code snippet. Actually, I think that the styles do not get “a lot of priority in the page” this way, quite the opposite. They should get deferred as described here.
    I have tweaked your example and used it in a WordPress theme. My version looks similar to this:
    /*
    * Defer noncritical CSS
    */
    add_filter('style_loader_tag', 'theme_defer_noncritical_css', 10, 2);

    function theme_defer_noncritical_css($html, $handle) {
    $noncritical = [
    'fontello',
    'mediaelement',
    // [...]
    ];

    if (in_array($handle, $noncritical)) {
    return str_replace(
    "rel='stylesheet'",
    "rel='preload' as='style' onload=\"this.onload=null;this.rel='stylesheet'\"",
    $html
    );
    }

    return $html;
    }

    1. Yes you are right, since the article publish and when I started using this snippet the new onload trick was discovered. In this way it isn’t load just switched and later parsed as stylesheet.
      The difference I think that it will be that the file it will be just downloaded but not parsed.

      I have to test it.

Leave a Reply

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