Inline Critical CSS From Your Theme
Prints the contents of a critical.css file from your active theme folder directly in the page head, so above-the-fold content is styled before the main stylesheet finishes loading.
Opens WPIDE on
Code
// File name inside the active theme folder.
$wpide_critical_file = 'critical.css';
add_action( 'wp_head', function () use ( $wpide_critical_file ) {
$path = get_stylesheet_directory() . '/' . $wpide_critical_file;
if ( ! is_readable( $path ) ) {
return;
}
$css = wp_cache_get( 'wpide_critical_css', 'wpide' );
if ( false === $css ) {
$css = (string) file_get_contents( $path );
$css = preg_replace( '#/\*.*?\*/#s', '', $css );
$css = trim( preg_replace( '/\s+/', ' ', $css ) );
wp_cache_set( 'wpide_critical_css', $css, 'wpide', HOUR_IN_SECONDS );
}
if ( $css ) {
echo '<style id="wpide-critical-css">' . wp_strip_all_tags( $css ) . "</style>\n";
}
}, 1 );
Notes
Generate a critical.css file (under 14 KB) with a critical CSS tool and put it in your (child) theme folder; nothing happens until the file exists.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.