Defer CSS loading with WordPress

So you're learning about Critical Rendering Path, you have already optimized your WordPress theme's stylesheet but still there are WordPress core CSS files that you want to lazy load. I have a present for you ๐ŸŽ

One of several techniques is to load the stylesheet using media="print" which tells the browser this file is meant for print view and not when regular browsing the page.

The trick is to use JavaScript to tell the browser that after finishing loading change that stylesheet from print to all, thus loading it for the regular view.

This will effectively defer the CSS loading until the end. In my case I want to defer the WordPress Block Library, I don't use it a lot and I saw a reduction of render time by applying this change:

function custom_use_print_block_library( $html, $handle ) {
  $handles = array( 'wp-block-library' );
  if ( in_array( $handle, $handles ) ) {
    $html = str_replace( 'media=\'all\'', 'media=\'print\' onload="this.onload=null;\'all\'"', $html );
  return $html;
add_filter( 'style_loader_tag', 'custom_use_print_block_library', 10, 2 );Code language: PHP (php)

To be placed in your functions.php theme's file.

Leave a Reply

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