This is an experiment in determining critical CSS for a given URL. It uses PhantomJS to load the URL and execute some JavaScript that:
- Extracts each of the CSS rules from all of the stylesheets on the page.
- Stylesheets without
screen
orall
media are skipped. - No other
@media
rules are filtered so that the critical CSS can apply to all screen sizes.
- Stylesheets without
- Gets all of the elements on the page whose bounding box is above the fold,
or has
display: none
(in which case the bounding box cannot be determined). - Finds the intersection of the CSS rules by determining whether any of the "visible" elements matches any of their selectors via Element.matches.
If you want to try it out, clone this repo then:
npm install
node test.js [url]
This will produce a bunch of artifacts in the working directory:
critical.css
: the "critical" stylesheet.before.html
andbefore.png
: the HTML source and a screenshot of the URL before the CSS is modified.nocss.png
: a screenshot of the URL after removing all of the CSS.after.html
andafter.png
: the HTML source and a screenshot of the URL after the critical CSS has been inserted into the<head>
.diff.png
: the visual diff orbefore.png
andafter.png
generated by Blink-diff.