In this tutorial, Today I will explain you how to enable and generate CSS critical path in Magento 2. 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. If we need to improve your site speed performance then, it’s one of the good point to implement on your Magento store.
The browser must download and parse CSS files before it shows the page. If CSS files size are too big and internet connection are too poor then, that files can increase the times to takes for web page to render.
So, Let’s see how to enable CSS Critical Path in Magento 2. You can enable it by this below command :
You may also like this :
php bin/magento config:set dev/css/use_css_critical_path 1
From Configuration :
Go to Admin -> Stores > Settings > Configuration > ADVANCED > Developer > CSS Settings > Use CSS critical path
Now, For generate critical.css file first of all, you need to install grunt in your Magento store. You can use this below article for install grunt in your Magento.
After that, You need to execute this below command from your Magento root folder :
npm install grunt-criticalcss --save-dev
In your Project’s grunt file, add below code for pass data object into grunt.initConfig()
grunt.initConfig({
criticalcss: {
home: {
options: {
url: 'https://www.rohanhapani.com',
width: 1400,
height: 900,
filename: 'css/style.css',
outputfile: 'css/critical-home.css'
}
},
blog: {
options: {
url: 'http://www.rohanhapani.com/blog/fix-scrolling-performance-css-will-change-property',
width: 1400,
height: 900,
filename: 'css/style.css',
outputfile: 'css/critical-blog.css'
}
}
}
});
You can execute home and blog both different sub task by below command :
grunt criticalcss:home
grunt criticalcss:blog
One more way (using critical-css-generator):
You need to install critical-css-generator package. You can check link here :
npm i critical-css-generator
and then, add this below code In your Magento instance root folder. Open your Gruntfile.js file and paste this below code.
const critical = require('critical-css-generator');
critical.generate({
url: 'https://www.rohanhapani.com',
path: '/var/www/html/m240/app/design/frontend/RH/Custom/web/css/test_critical.css',
viewport: true
});
You need to execute grunt exec code.
That’s it !!!
You can see changes in your view page source. You can find out data-type=”criticalCss” text in your view page source.
Output :
I hope this blog is easy to understand how to enable and generate CSS critical path in Magento 2.In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with a proper solution.
Stay Safe and Stay Connected !!