2

How to auto Generate Critical Path CSS using Penthouse or Critical for Magento 2.

Reff:

https://devdocs.magento.com/guides/v2.3/frontend-dev-guide/css-topics/css-critical-path.html

https://www.npmjs.com/package/penthouse

https://www.npmjs.com/package/critical

1 Answer 1

3

You can use magento-2-gulp implementation to compile critical CSS.

If you use default Magento grunt, you can install grunt-penthouse and add new task.

grunt.initConfig({
  penthouse: {
    extract : {
        outfile : '.tmp/out.css',
        css : './dist/css/full.css',
        url : 'http://localhost:9000',
        width : 1300,
        height : 900,
        skipErrors : false // this is the default
    },
  },
});

The same for the gulp-penthouse if you have your own gulp configuration.

var gulp = require('gulp');
var criticalCss = require('gulp-penthouse');

gulp.task('critical-css', function () {
    return gulp.src('./styles.css')
        .pipe(criticalCss({
            out: 'critical.css',
            url: 'http://localhost:9000',
            width: 1300,
            height: 900,
            strict: true,
            userAgent: 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
        }))
        .pipe(gulp.dest('./dist/css/'));
});

Example for gulp:

var gulp = require('gulp');
var criticalCss = require('gulp-penthouse');

gulp.task('critical-css', function () {
    return gulp
        .src([
            'pub/static/frontend/<VendorName>/<ThemeName>/en_US/css/styles-l.css', 
            'pub/static/frontend/<VendorName>/<ThemeName>/en_US/css/styles-m.css'
        ], {
            base: 'pub/static/frontend/<VendorName>/<ThemeName>/en_US/css/'
        })
        .pipe(criticalCss({
            out: 'critical.css',
            url: 'http://<yoursite>.loc',
            width: 1300,
            height: 900,
            strict: true,
            userAgent: 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
        }))
        .pipe(gulp.dest('app/design/frontend/<VendorName>/<ThemeName>/web/css'));
});
1
  • should we use the above snippet inside the module.exports = function (grunt) {}) of Gruntfile.js in Magento root and simply run grunt exec? or are there any steps to follow?
    – Dev
    Jul 6, 2022 at 12:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.