I am having trouble preloading CSS on my WordPress site. I was writing a script to find every JS and CSS script enqueued in the footer, and preload it in the <head>
. The code for the JS scripts works fine (when I go to page source on the site, I can see the <link>
tags with the preload attribute inside), but the CSS preload link tags aren't showing up.
It is very likely I am doing this completely wrong, as I found working code for the JS scripts and then tried to alter it to get it to work for the CSS. For instance, I don't think the version appendage applies to CSS, but I assumed it would still work since it would default to false, right?
As a related question, I am having the same issue with webfonts. Google Pageview Insights is telling me to preload webfonts, so I added some php to do that, but when I run pageview insights again, no dice.
Here is the code:
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'/>
";
}
}
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\"'/>
<noscript><link rel='stylesheet' href='{$source}'/></noscript>
";
}
}
//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);
</div>