Generate Critical CSS and Load Full Stylesheets Asynchronously in WordPress

Critical CSS and an asynchronous stylesheet in WordPress

A stylesheet in the <head> blocks rendering: the browser shows nothing until it has downloaded and parsed the file. Critical CSS splits the work: the few rules needed for the first screen are inlined in the page, and the full stylesheet loads without blocking. The first paint then needs only the HTML, which improves First Contentful Paint and often Largest Contentful Paint.

Problem: Lighthouse reports “Eliminate render-blocking resources” for the theme’s stylesheet, and on a slow phone connection the page stays white for over a second.

Solution: Generate the critical CSS per page type with the critical npm package at build time, print the matching file inline in wp_head, and change the theme stylesheet’s <link> with the style_loader_tag filter so it loads with media="print" and switches to all on load, with a <noscript> fallback.

Generate the critical CSS

npm install --save-dev critical
// build/critical.mjs, run with: node build/critical.mjs
import { generate } from 'critical';

const pages = [
    [ 'https://example.test/', 'home' ],
    [ 'https://example.test/sample-post/', 'single' ],
    [ 'https://example.test/category/news/', 'archive' ],
];

for ( const [ src, name ] of pages ) {
    await generate( {
        src,
        target: `assets/critical/${ name }.css`,
        width: 1300,
        height: 900,
        inline: false,
    } );
    console.log( 'critical CSS:', name );
}

Run it against the local or staging copy after each change of the theme’s CSS; a stale critical file shows the first screen briefly in the old design.

Inline it

add_action( 'wp_head', 'ha_critical_css', 1 );

function ha_critical_css() {
    $type = is_front_page() ? 'home' : ( is_singular() ? 'single' : 'archive' );
    $file = get_theme_file_path( "assets/critical/{$type}.css" );
    if ( is_readable( $file ) ) {
        echo '<style id="ha-critical">' . wp_strip_all_tags( file_get_contents( $file ) ) . "</style>\n";
    }
}

Reading a small file from disk is cheap, and with a page cache it happens once per page anyway; caching it in a transient brings nothing.

Load the full stylesheet without blocking

add_filter( 'style_loader_tag', function ( $html, $handle, $href ) {
    if ( 'ha-style' !== $handle || is_admin() ) {
        return $html;
    }
    $async = str_replace( "media='all'", "media='print' onload=\"this.media='all'\"", $html );
    return $async . '<noscript>' . $html . "</noscript>\n";
}, 10, 3 );

ha-style is the handle of the theme stylesheet in wp_enqueue_style(). A stylesheet with media="print" does not block rendering on screens; once it has loaded, the onload handler switches it to all media. Without JavaScript, the normal <link> in <noscript> applies.

Check

Compare the page with the network throttled to “Slow 3G”: the first screen should appear in its final design, and there should be no visible jump when the full stylesheet arrives. A jump means the critical CSS is missing rules for the first screen (often the header, fonts or the hero image size).

NOTE: This technique pays off for large stylesheets. If the theme’s CSS is small after compression, inlining all of it or just removing unused rules is simpler; see removing unused CSS with PurgeCSS. Deferring scripts is covered in defer JavaScript and CSS loading.