I have a site that is using Gulp.js as its task runner. I wanted to use criticalCSS on the site and because there isn’t a Gulp plugin quite yet, I had to roll it myself.
I’m going to try and tackle writing the plugin myself, but for the time being, here is a quick script to get it running:
gulp.task('critical', function() {
var request = require('request');
var path = require( 'path' );
var criticalcss = require("criticalcss");
var fs = require('fs');
var tmpDir = require('os').tmpdir();
var cssUrl = 'http://localsite.dev/wp-content/themes/theme_name/style.css';
var cssPath = path.join( tmpDir, 'style.css' );
var includePath = path.join( __dirname, 'inc/critical.css.php' );
request(cssUrl).pipe(fs.createWriteStream(cssPath)).on('close', function() {
criticalcss.getRules(cssPath, function(err, output) {
if (err) {
throw new Error(err);
} else {
criticalcss.findCritical("http://localsite.dev/", { rules: JSON.parse(output) }, function(err, output) {
if (err) {
throw new Error(err);
} else {
fs.writeFile(includePath, output, function(err) {
if(err) {
return console.log(err);
}
console.log("Critical written to include!");
});
}
});
}
});
});
});
As you’ll probably notice, this is a WordPress site, but you can tweak some of the parameters in here to meet your needs. I have the inlined css outputting into an include called critical.css.php
. You can reference my post on Using criticalCSS in WordPress on how to output this include in your <head>
.
2 replies on “Using criticalCSS with Gulp.js”
This made my life so much easier. Thank you! Any luck building the Gulp plugin yet?
Glad it helped you!
I never did get around to building one. Still not off the table, just haven’t had time to do it.