I’m using WordPress, but this question could probably apply to other PHP-driven templating system.
I’d like to have a css file (i.e. critical.css) that contains all the styles for important global elements & above-the-fold content (e.g. typography, header includes, navigation, site-wide banners/heros), kept separate from my modular content, page-specific styles & footer styles. I then want to take the contents of this file and print it between style tags right below the document title tag.
The goal is to improve above-the-fold rendering speed. I’ve noticed a definite improvement in the rendering of above-the-fold content when those styles are prioritized (along with any resets), even if those improvements are more experiential than technical.
But…I’m having trouble figuring out how to “print” the inline styles from this document into the wp_head.
I’ve explored wp_add_inline_style and this does not seem to offer the functionality I’ll need. It appears you have to define those styles within a function, and that’s definitely not what I’m going after.
- Does there exist a method for hooking inline styles taken from my critical.css file into the wp_head? wp_print_styles is either deprecated or not recommended according to the Codex.
- If not, what is the preferred method of emphasizing these critical styles in WordPress? Preferably, a method that’s not render-blocking or doesn’t rely on a metabox.
I’m trying to avoid using a PHP include (i.e. dumping everything between PHP tags in a critical-styles.php file and then calling that in the wp_head) in favor of something cleaner or that can be achieved with functions.php or WordPress’s native hooks. With all the emphasis on Pagespeed optimization these days, I was surprised that this hadn’t been asked here in a WordPress context. Any help on this or methods that have worked better for you are greatly appreciated.
You can simply
include
the actual CSS file in header.php:PHP’s
include()
function doesn’t require that the included file also has to be PHP.Alternatively, if you want to keep things in functions.php, you could do a
file_get_contents()
and hook into thewp_head
action hook: