Load CSS Asynchronously


Some CSS loaded by theme, and others loaded by plugin => Its very hard to choose “critical CSS” to load first and defer the others (non-critical css). 

How to do: 

+ LoadCSS script: need to test & implement. This script provides a JS function to load CSS dynamically & add <link rel=”preload”> to make stylesheet load asynchronously & “onload” to apply the style to pages when the css file is loaded 

Interesting source: https://jasonbaciulis.com/wordpress-performance-optimization/#server-side_caching

+ Using functions to add “preload” tag to css and inline critical CSS to head:

First, add tag rel=”preload” to css files:

function add_rel_preload($html, $handle, $href, $media) {if (is_admin())return $html;$html = <<<EOT<link rel='preload' as='style' onload="this.onload=null;this.rel='stylesheet'" id='$handle' href='$href' type='text/css' media='all' />EOT;return $html;}add_filter( 'style_loader_tag', 'add_rel_preload', 10, 4 );

Second, Insert the critical CSS into <head> by this function:

function hook_css() {?>[insert critical css here]<?php}add_action('wp_head', 'hook_css');


+ Critical CSS needs to stay in these tags: <style>critical CSS</style>

+ We need to using right tools to create critical CSS => Which tool?

+ We should combine critical CSS of all page types (page/post/product) and inline it in <head>. If the combined critical CSS is too heavy, we can use WP-Rocket or autoptimize paid solution (these tools can dynamically create critical CSS).