Categories
Scripts

Using criticalCSS with Gulp.js

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>.

By Ryan Tvenge

I'm a web developer and co-owner of Hoverboard that makes cool stuff on the web.

2 replies on “Using criticalCSS with Gulp.js”

This made my life so much easier. Thank you! Any luck building the Gulp plugin yet?

Leave a Reply

Your email address will not be published. Required fields are marked *

Tvenge Design