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
To enqueue style file, you need to use
wp_enqueue_style
function. You usedwp_enqueue_script
which is used to enqueue JavaScript file.And you need to use
style_loader_tag
filter to filter the HTML link tag of an enqueued style.But you used
script_loader_tag
filter which is used to filter<script>
tag.(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