Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.