在 WordPress 中向 css 文件添加预加载

Ski*_*tas 3 wordpress

我是 WordPress 新手,正在尝试预加载某些 css 文件。我知道它们是使用 加载到 head 中的wp_enqueue_style(),所以我尝试访问从中生成的 html 来添加rel="preload"

到目前为止看起来像这样

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;
} 
Run Code Online (Sandbox Code Playgroud)

虽然当我添加此preload_filter函数时,我的 css 无法完全加载,而不仅仅是指定的样式表......我在尝试执行此操作时是否遗漏了任何内容,或者是否有更简单的方法?任何帮助将不胜感激。

Web*_*102 7

要排队样式文件,您需要使用wp_enqueue_style函数。您使用了wp_enqueue_script它来将 JavaScript 文件排入队列。

wp_enqueue_style('preload-style', 'styles/main-style.css', false, null);
Run Code Online (Sandbox Code Playgroud)

并且需要使用style_loader_tagfilter来过滤入队样式的HTML链接标签。

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;
}
Run Code Online (Sandbox Code Playgroud)

但是您使用了script_loader_tag用于过滤<script>标签的过滤器。