📜 ⬆️ ⬇️

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

In the good old days, we with Google PageSpeed ​​Insights were on a short leg. I riveted cheap templates, Google put a high mark on the speed of their loading. However, over time, much has changed, and even though I still rivet cheap templates, Google began to stick my wheels in me.

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


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

Automatic generation of critical CSS


The Internet has already accumulated enough information on this topic. In a nutshell, Google declares that I should postpone the loading of styles that do not affect the display of the top of my page, which falls into the viewport immediately after the page loads, and insert the necessary styles directly into the html code.
')
I decided to select the necessary styles manually as an impossible task, so I started searching for a tool 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 with the first two I somehow didn’t work, 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('<!-- Critical CSS -->', '\n<style>\n' + criticalCss + '\n</style>')) .pipe(gulp.dest('dist')) }); }); 

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

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

How to connect the remaining files with styles?


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

Source: https://habr.com/ru/post/316970/


All Articles