Load Selected Stylesheets Without Blocking Rendering
Loads the stylesheets you choose in the background so they no longer delay the first paint, ideal for CSS of things below the fold like sliders or forms.
Opens WPIDE on
Code
// Style handles to load asynchronously. Find handles in the page source: id="HANDLE-css".
$wpide_async_styles = array( 'contact-form-7' );
add_filter( 'style_loader_tag', function ( $tag, $handle ) use ( $wpide_async_styles ) {
if ( ! in_array( $handle, $wpide_async_styles, true ) || false !== strpos( $tag, 'onload=' ) ) {
return $tag;
}
$async = preg_replace( "/media=(['\"])(all|screen)\\1/", 'media="print" onload="this.media=\'all\';this.onload=null;"', $tag, 1, $count );
return $count ? $async . '<noscript>' . $tag . '</noscript>' : $tag;
}, 10, 2 );
Notes
Do not use it for the main theme stylesheet, or visitors will briefly see unstyled content.
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.