skip to Main Content

I am new to WordPress and am trying to preload certain css files. I understand that they are loaded into the head using wp_enqueue_style(), so I am trying to access the html generated from that to add rel="preload".

So far it looks like this

wp_enqueue_script('main-style', 'styles/main-style.css', false, null);

add_filter('script_loader_tag', 'preload_filter', 10, 2);

function preload_filter($html, $handle) {
   if (strcmp($handle, 'main-style') == 0) {
      $html = str_replace("rel='stylesheet'", "rel='preload' as='style' ", $html);
   }

   return $html;
} 

Although when I add this preload_filter function my css fails to load completely, and not just for the specified stylesheet… Am I missing anything in trying to do this, or is there a simpler method? Any help would be greatly appreciated.

2

Answers


  1. To enqueue style file, you need to use wp_enqueue_style function. You used wp_enqueue_script which is used to enqueue JavaScript file.

    wp_enqueue_style('preload-style', 'styles/main-style.css', false, null);
    

    And you need to use style_loader_tag filter to filter the HTML link tag of an enqueued style.

    add_filter( 'style_loader_tag',  'preload_filter', 10, 2 );
    function preload_filter( $html, $handle ){
        if (strcmp($handle, 'preload-style') == 0) {
            $html = str_replace("rel='stylesheet'", "rel='preload' as='style' ", $html);
        }
        return $html;
    }
    

    But you used script_loader_tag filter which is used to filter <script> tag.

    Login or Signup to reply.
  2. (Can’t reply, but extends this answer https://stackoverflow.com/a/66640766/1898675)

    This modification use the noscript fallback, which is recommended by google for defer css. https://web.dev/defer-non-critical-css/#optimize

    add_filter( 'style_loader_tag',  'preload_filter', 10, 2 );
        function preload_filter( $html, $handle ){
        if (strcmp($handle, 'preload-style') == 0) {
            $fallback = '<noscript>' . $html . '</noscript>';
            $preload = str_replace("rel='stylesheet'", "rel='preload' as='style' onload='this.rel="stylesheet"'", $html);
            $html = $preload . $fallback;
        }
        return $html;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search