Adding preload to css files in WP

Rate this post

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.



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.

Leave a Reply

Your email address will not be published.

Back to top button