metalsmith-inline-critical-css
A Metalsmith plugin to inspect HTML files, inline used selectors from specified CSS, and load the rest asynchronously.
Motivation
When the browser encounters a <link rel="stylesheet">
in the <head>
, it pauses, goes to the network, fetches the file, and only then continues.
This is called "render blocking".
If it sounds bad for performance, it's because it is!
This is especially true for slower networks where the latency alone can add seconds to the request.
To combat this, you can "inline" the used or critical CSS for a page as a <style>
tag.
You then load the rest asynchronously.
To do that, you link the stylesheet as <link rel="preload">
, which decouples downloading from execution, and allows the browser to continue.
Once the stylesheet has loaded, it is "swapped in".
To account for browsers that do not support rel="preload"
, we use the excellent LoadCSS relpreload.js.
Inlining the critical CSS for a page is one of the most important optimisations you can do to make your site paint faster!
Quick start
This package is distributed via npm.
$ npm install --save metalsmith-inline-critical-css# or $ yarn add metalsmith-inline-critical-css
Then you can use the plugin in your metalsmith pipeline:
const fs = ;const path = ;const metalsmith = ;const criticalCss = ; // Set these as you want for your applicationconst INPUT_DIR = '_site/';const OUTPUT_DIR = '_site/'; { // Run metalsmith pipeline sourceINPUT_DIR // source directory // destination directory // clean destination before ;} ;
Options
Credits, Thanks, Inspiration
Thanks to Filament Group for their work on Load CSS!