I am generating critical CSS for every page and category. At the moment I am inserting the stylesheet through functions.php
like this simply using echo
.
function criticalCSS_wp_head() {
if (is_front_page() ){
echo '<style>';
include get_stylesheet_directory() . '/css/critical/ccss-index.min.css';
echo '</style>';
}
elseif (is_category('orange') ){
echo '<style>';
include get_stylesheet_directory() . '/css/critical/ccss-orange.min.css';
echo '</style>';
}
elseif (is_page('hello-world') ){
echo '<style>';
include get_stylesheet_directory() . '/css/critical/ccss-hello-world.min.css';
echo '</style>';
}
elseif (is_single() ){
echo '<style>';
include get_stylesheet_directory() . '/css/critical/ccss-single.min.css';
echo '</style>';
}
}
add_action( 'wp_head', 'criticalCSS_wp_head' );
- What would be the best way to include these stylesheets with regards to best practise coding style and pure relentless speed, meaning to avoid PHP calls, database calls and so on.
- Is it better to directly hard-code the critical CSS in the page template perhaps like written in this post (#10) linked from the official WordPress Optimization documentation?
edit
Since this question was answered I forgot to mention that critical CSS needs to be inline in the DOM and not being linked to as a file to avoid render blocking. So I am still looking for a way to use the critical CSS with wp_enqueue_scripts
. Perhaps store the file content in a variable and output that when wp_enqueue_scripts
asks for it?