Above-the-Fold CSS - how to speed up website loading without slowing down development

In the good old days, Google PageSpeed ​​Insights and I were on a short foot. I - riveted cheap templates, Google - praised the speed of their download. However, over time, a lot has changed, and although I still rivet cheap templates, Google began to put sticks in my wheels.

I think many have seen the following comments in Google PageSpeed ​​Insights reports:

  • Shorten CSS (HTML, JavaScript)
  • Use browser cache
  • Turn on compression
  • Remove JavaScript and CSS blocking the top of the page

And if, as a rule, there are no problems with the first three points, the last point has puzzled me.

Automatic generation of critical CSS


Enough information has already accumulated on the Internet on this subject. In a nutshell, Google states that I should postpone loading styles that do not affect the display of the top of my page, which gets into the viewport immediately after the page loads, and insert the necessary styles directly into the html code.

I considered the task of manually highlighting the desired styles impossible; therefore, I began to search for a means to automate this process. To date, I have found only three tools created to generate the necessary styles:

  1. Critical CSS
  2. Critical
  3. Penthouse

And if I somehow didn’t get it right with the first two, Penthouse turned out to be exactly the tool I was looking for. Since I use Gulp to build projects, the code for gulpfile.js will be presented below.

1. Install the necessary modules:

$ npm install --save-dev penthouse
$ npm install --save-dev gulp-inject-string

2. Open gulpfile.js and connect them:

var penthouse = require('penthouse');
var inject = require('gulp-inject-string'); // необходим для вставки стилей непосредственно в код html

3. Next, you need to specify the path to your page and styles:

gulp.task('penthouse', function () {
  penthouse({
    url: 'src/index.html', // страница вашего сайта
    css: 'src/css/styles.css', // файл со стилями
    width: 1280,
    height: 800
  }, function (err, criticalCss) {
  gulp.src('src/index.html')
    .pipe(inject.after('', '\n'))
    .pipe(gulp.dest('dist'))
  });
});

In this example, styles will be inserted immediately after the Critical CSS comment in the index.html file.

Done! Now Google PageSpeed ​​Insights will stop swearing at this item, and move it to the "Fulfilled Rules" tab.

How to connect other files with styles?


Many people advise connecting them asynchronously using JavaScript, but for myself I found a rather simple way out - connecting them at the end of the html code before the closing body tag, but before JavaScript. Someone will say that releasing elements with the rel attribute outside the head limits is not valid , but HTML5.0 has sunk into oblivion since October, and the WHATWG specification does not prohibit this.

Also popular now: