【发布时间】:2019-07-15 20:20:15
【问题描述】:
我在我的 WordPress 网站上预加载 CSS 时遇到问题。我正在编写一个脚本来查找在页脚中排队的每个 JS 和 CSS 脚本,并将其预加载到 <head> 中。 JS 脚本的代码工作正常(当我转到网站上的页面源时,我可以看到内部带有 preload 属性的 <link> 标签),但是 CSS 预加载链接标签没有显示出来。
很可能我这样做完全错误,因为我找到了 JS 脚本的工作代码,然后尝试更改它以使其适用于 CSS。例如,我不认为版本附件适用于 CSS,但我认为它仍然可以工作,因为它会默认为 false,对吗?
作为一个相关问题,我对 webfonts 也有同样的问题。 Google Pageview Insights 告诉我预加载 webfonts,所以我添加了一些 php 来做到这一点,但是当我再次运行 pageview Insights 时,没有骰子。
代码如下:
add_action('wp_head', function () {
global $wp_scripts;
global $wp_styles;
foreach($wp_scripts->queue as $handle) {
$script = $wp_scripts->registered[$handle];
//-- Check if script is being enqueued in the footer.
if($script->extra['group'] === 1) {
//-- If version is set, append to end of source.
$source = $script->src . ($script->ver ? "?ver={$script->ver}" : "");
//-- Spit out the tag.
echo "<link rel='preload' href='{$source}' as='script'/>\n";
}
}
foreach($wp_styles->queue as $handle) {
$style = $wp_styles->registered[$handle];
if ($style->extra['group'] === 1) {
$source = $style->src . ($style->ver ? "?ver={$style->ver}" : "");
echo "<link rel='preload' href='{$source}' as='style' onload='this.rel = \"stylesheet\"'/>\n
<noscript><link rel='stylesheet' href='{$source}'/></noscript>\n";
}
}
//This is the code to preload webfonts
echo "<link rel='preload' href='/wp-content/themes/salient/css/fonts/fontawesome-webfont.woff?v=4.2' as='font' type='font/woff'>";
echo "<link rel='preload' href='/wp-content/themes/salient/css/fonts/fontawesome-webfont.ttf?v=4.2' as='font' type='font/ttf'>";
}, 1);
【问题讨论】: