Reduce render-blocking stylesheets
Since Lighthouse is built-in into Chrome, it’s now easier than ever to test your sites even on your local machine. Yesterday I decided to get an all meters to grow in green.
The big major issue on “Performance” was “reduce render-blocking stylesheet.” If a resource is “render-blocking”, it means the browser can’t display the page until the resource is downloaded or otherwise dealt with.
I would not consider this to be the first thing out many small things add up. Typically, we will load our CSS in a render-blocking way by linking to our stylesheet in the head of the document. For a large site, particularly one with a generously-sized framework like Bootstrap, the stylesheet might be several hundred kilobytes, and the user will have to wait until this full downloads patiently.
If the page rendered without any of our CSS loaded and add the styles at the end of the document, we’d get the ugly “flash of unstyled content”
Before I tried to manually identifying the critical CSS would be a pain to maintain. To do it programmatically, we can use Addy Osmani’s aptly named Critical, which will load and identify the critical CSS is by loading the page with PhantomJS. Further, there is an extension for Laravel Mix, if you are using Laravel like me.
First, install laravel-mix-critical by Rias500.
npm install laravel-mix-critical --save-dev
Not that Critical requires a reasonably recent version of Laravel Mix that has extended (). Make sure to update Laravel Mix.
let mix = require('laravel-mix');
require('laravel-mix-critical');
mix
.js('resources/assets/js/app.js', 'public/js')
.less('resources/assets/less/app.less', 'public/css')
.critical({
enabled: mix.inProduction(),
urls: [
{ src: 'https://mywebsite.com', dest: 'public/css/index_critical.min.css' },
],
options: {
minify: true,
},
});
Since the site is powered by a CMS, I am using the output from the actual site to extract the critical CSS. Otherwise, you can read the base URL from .env.
process.env.BASE_URL + '/'
Hopefully, it will run without you dumping the node_modules-directory.
npm run prod
Now you should have extracted version of your CSS that you can include on the head of your page to prevent FOUT.