I have a simple multi-page app with three pages, my webpack.config.js
entry
looks like:
{
entry: {
a: 'pages/a.js',
b: 'pages/b.js',
c: 'pages/c.js',
}
}
Each page consists of several React components, some of which are visible above-the-fold on first render, and some of which are out of view.
I'd like to declaratively define which components are 'critical' (above-the-fold) for each page/entry, and have that CSS extracted into a separate file. Something like:
{
a: ['compononents/button/style.css', ...],
b: ['compononents/title/style.css', ...],
c: ['compononents/header/style.css', ...]
}
outputting something like:
- dist/a.critical.css
- dist/b.critical.css
- dist/c.critical.css
I've been playing around with the extract-text-webpack-plugin, but can't seem to find a way to tell it to only extract specific CSS in the context of a specific entry.
How can I extract specific CSS file content when in the context of a specific entry/page?
By placing Critical CSS in the head tag of our HTML file instead of in an external stylesheet, we solve both issues. First, the browser doesn't have to render the whole page before visualizing above-the-fold content. It can find the Critical CSS easily because it doesn't need to look in a separate location.
Once the package has been installed, you need to create a JavaScript file in the project directory and put the following code in it. var critical = require('critical'); critical. generate({ inline: true, base: 'initial/', src: 'homepage. html', dest: 'final/homepage.
The goal of inlining critical CSS is to prevent a flash of unstyled content (FOUC). CSS is a render-blocking resource, meaning that it needs to be downloaded and parsed to create the CSSOM.
Above the fold content is the part of a web page shown before scrolling. Any content you'd need to scroll down to see, would be considered 'below the fold'. The 'fold' is where the browser window ends, but the content continues underneath.
I'm in the same situation, our project is big enough and we need more than 20 different critical css files. I found a way to make generating critical CSS more painless. I'm using https://github.com/zgreen/postcss-critical-css which allow creating different critical css files.
@critical crit.css {
.head {
background: red;
}
.head .logo {
display: block
}
}
@critical v2.css {
.head.v2 {
background: green;
}
}
.main {
color: #333;
}
.footer {
background: black;
}
Postcss-critical-css will generate 3 files - my css file (with or without critical styles) and 2 critical css files - v2.css and crit.css
Hope this will help you!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With