Optimising javascript files

In this next great installment of my new development process I want to head back to looking at javascript files, as my last three posts have been about adding stylesheets in my processlazy loading stylesheets that are non-critical and using resource hints (although technically that last one applies to any resources, not just stylesheets).

The last time I wrote about javascript files, I had them beautifully minified and ready to go.  My gulp task for javascript files currently looks like this…

gulp.task("js",function(cb) {
  pump([
    browserify(jsFiles).bundle(),
    source("script.js"),
    buffer(),
    uglify(),
    gulp.dest("build/js")
  ],cb);
});

If you have a lot of javascript, especially with immediately-invoked function expressions (IIFEs), it can be a good idea to optimise them.  This essentially works by indicating to the browser’s javascript engine during pre-parsing that it can skip this function as it can be fully parsed later, and this stops it from being parsed twice.

For more details, I would definitely recommend checking out the Github page for the plugin I’m about to talk about, which is optimize-js.  Once again, there is a thin wrapper Gulp plugin, called gulp-optimize-js.

Side note: The naming convention isn’t a coincidence, it’s actually a naming convention!

Anyway, so if you’ve been reading this series of posts, you’ve probably already picked up on the pattern here.  I installed the plugin from NPM, then require it at the top of my Gulp file…

var optimize = require("gulp-optimize-js");

And then I add the relevant call into my javascript Gulp task…

gulp.task("js",function(cb) {
  pump([
    browserify(jsFiles).bundle(),
    source("script.js"),
    buffer(),
    uglify(),
    optimize(),
    gulp.dest("build/js")
  ],cb);
});

It’s very important to make sure that you call this plugin after you’ve called gulp-uglify, because minifying the code will remove the optimisation that has been added, as technically it’s done by adding additional brackets into your code.  However, these extra characters should be worth it overall.

I’ve tried testing with and without this optimisation on my own website, and I can’t tell the difference.  The reason for this is that I don’t have enough javascript code, but maybe you do.  I like knowing that my development process is as good as it can be though, even if in this case, the results are not tangible.

This plugin is covered in my Skillshare course, Optimising your website: A development workflow with Git and Gulp. The relevant video is 12 – Optimising Javascript Files.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.