Inline critical CSS
- Performance
External stylesheets block rendering — the browser won’t paint anything until they’re downloaded. Inlining the CSS needed for above-the-fold content directly in the HTML eliminates this bottleneck. The rest of the CSS can load asynchronously.
<?php
/**
* Inline Critical CSS
*
* Embeds a small CSS file directly in the <head> to style above-the-fold
* content without waiting for an external stylesheet to download. This
* eliminates the render-blocking delay on first paint. Keep the critical
* CSS under 14 KB (one TCP round-trip) for maximum benefit.
*
* Usage: Add to functions.php. Create the critical CSS file at the path
* specified below. Generate it with tools like Critical or PurgeCSS.
*
* @category performance
* @language php
*
* @author Adame Dahmani https://adame.io
* @support Support my family project: https://adame.io/fundraiser
*/
add_action( 'wp_head', function () {
$critical_path = get_template_directory() . '/assets/critical.css';
if ( ! file_exists( $critical_path ) ) {
return;
}
echo '<style id="critical-css">';
echo file_get_contents( $critical_path );
echo '</style>';
}, 1 );Keep the critical CSS under 14 KB — that’s the amount of data that fits in the first TCP round-trip. Generate it with tools like Critical or the Penthouse library.