CSS critical path
All CSS styles loaded from external files are considered as render-blocking. It means that web page will not be displayed until these files are loaded.
By using ‘CSS critical path’, we deliver minified critical CSS inline in
<head> and defer all non-critical styles that are loaded asynchronously.
Thus we can significantly improve the time to first render of our pages.
Enable CSS critical path
CSS critical path configuration is located in Stores > Settings > Configuration > ADVANCED > Developer tab. But Developer tab is hidden in [production mode][production-mode]. Once in production mode, CSS critical path can only be enabled using the CLI.
Enable CSS critical path:
1 2 3 ```bash bin/magento config:set dev/css/use_css_critical_path 1 ```
Make sure that there is a
critical.css file for your theme. Other non-critical CSS files will be loaded asynchronously.
Overview of Magento’s critical CSS
The ‘critical’ CSS file should be located in
Default Luma theme critical CSS file is located in
If there is not
critical.css for the custom theme but there is Luma theme, Luma’s
critical.css will be used.
THe critical css file path can also be configured in
di.xml as a constructor
filePath argument in the
To generate a critical CSS for your theme, critical path CSS generators like Penthouse or Critical can be used,or you can create it yourself. While creating critical CSS, adhere to the following principles:
- Minify your
critical.cssto reduce its size.
- Do not duplicate styles in
critical.cssand non-critical style sheets.
- Do not introduce new styles in
critical.cssthat are not present in non-critical style sheets. CSS rules from non-critical style sheets should overwrite critical CSS rules. Otherwise your styles can be broken.
Critical CSS loader
If ‘CSS critical path’ is enabled in the configuration, a preloading spinner will be used. It is added in
After non-critical CSS is loaded and applied, the spinner disappears. The spinner will disappear automatically only if you have CSS styles from the ‘Blank’ theme CSS. If you have your own CSS rules, you should hide the preloader by using the
Critical CSS performance improvements
Introducing a critical path CSS to Magento leads to performance improvements:
- Eliminated render-blocking CSS resources. As a result, time for loading render-blocking resources decreases substantially.
- First meaningful paint time improved from 3.5 sec to 2.3 sec.
- Speed index increased by 0.8 sec.
As a result Google PageSpeed Insights score improved by 5 points.
These are results for mobile devices with slow connection from Google PageSpeed Insights