What is Critical CSS in Magento 2?
Critical CSS is a technique that extracts CSS for the top half of the page (without scrolling down) to render content to the user as quickly as possible. In simple words, everything we see on a web page without scrolling is critical CSS.
Let’s say you have a complicated website with many CSS files. The home page will not be rendered until all of these CSS files are loaded, so we can create a critical CSS file that has all the styles needed to generate the basic structure of the home page. As a result, the home page will be displayed and all non-critical CSS files will be loaded asynchronously.
Use of critical CSS in Magento 2
Before rendering a page, the browser must download and parse CSS files, which makes CSS a view-blocking resource. If CSS files are large or network conditions are poor, CSS file requests can significantly increase the time it takes for a web page to render.
Using embedded critical CSS in the header increases rendering speed and performance, especially in poor network conditions. All non-critical styles will be loaded asynchronously, allowing us to drastically reduce the time it takes to first render our web pages.
How to enable critical CSS?
1. Using the Administrator Panel
To enable critical CSS from the admin panel, go to
Stores > Settings > Configuration > ADVANCED > Developer Tab > CSS Settings
Note: In production mode, the developer tab is disabled, in which case you must enable it from the command line (CLI).
2. Using the command line (CLI)
To enable critical CSS via the command line, type the following command:
php bin/magento config:set dev/css/use_css_critical_path 1
Note: Make sure your theme contains a Critical.css file while the other non-critical path will load asynchronously.
How to set critical CSS?
The ‘critical’ CSS file should be located in,
app/design/frontend/<your_vendor_name>/<your_theme_name>/web/css/critical.css
The default CSS file critical to the Luma theme is located in,
app/design/frontend/Magento/luma/web/css/critical.css
The critical path of the CSS file can also be configured in the
app/design/frontend/Magento_theme/layout/default_head_block.xml
That’s all you need to do. Hope this helps.
Reference: Magento DevDocs CSS Critical Path
You can also check out our other related blogs
How to remove JS and CSS in Magento 2 using XML layout
Understanding Magento theme