CSS

Critical CSS

Critical CSS is a technique that extracts the CSS for above-the-fold content in order to render content to the user as fast as possible. Above-the-fold is all the content a viewer sees on page load, before scrolling.
Every kind of pages (ex: home, category, single..) has different CSS. You can find it's name by view the page source:
The critical CSS files are located in directory wp-content/uploads/critical-css
This hook helps you to insert stuffs before critical CSS or determine whether there are critical css or not.
1
//do exist or not exist,
2
add_action('print_critical_css', function($css) {
3
//when no exist critical: fix css before generate critical css
4
if(!$css) {
5
echo '<style>.gem-icon .gem-icon-half-1,body:not(.compose-mode) .gem-icon .gem-icon-half-2{opacity:0!important;}</style>';
6
}
7
//font , used with `font-display:optional`
8
foreach(hpp_criticalcss_extract_fonts($css) as $i=>$font_url) {
9
if($i<5 ) printf('<link rel="preload" as="font" href="%s" crossorigin>', $font_url);
10
}
11
});
Copied!
You can share the same CSS between the pages, so you don't need to generate duplicate CSS for those pages.
1
//use same critical file
2
add_filter('get_criticalcss_path', function($file, $uri){
3
if(hpp_in_str($uri, ['/about-us/','/contact/'])) {
4
return WP_CONTENT_DIR.'/uploads/critical-css/page-page.css';
5
}
6
return $file;
7
}, 10, 2);
Copied!
To edit the content of critical CSS, you have 2 ways: by editing CSS file directly OR via hook:
1
add_filter('hpp_critical_css', function($css, $file){
2
if(strpos($file, '.mobile.css')===false) {
3
$css .= '.example-class{height: 100px;}';
4
}
5
return $css;
6
}, 10, 2);
Copied!

Lazy CSS

Some Inline CSS on the page can load resources such as background image, font-face. So we will extract the CSS code that contains resources & group all of them in a separate tag named <style media="not all" . This technical called lazy CSS, help to reduce the page load time. Now, You can modify this lazy CSS by using the code like this:
1
add_filter('hpp_lazycss', function($css) {
2
// $css = str_replace('find', 'replace', $css);
3
return $css;
4
});
Copied!
Last modified 6mo ago
Copy link