Back to Website Launch Checklist

How to minify and concatenate your website's CSS and JavaScript files

How to minify and concatenate your website's CSS and JavaScript files

Whenever a user connects to your website, the server sends multiple files to their computer. The smaller these files are, and the fewer of these files there are in total, the faster they can be transmitted. Minifying (a means of compression) and concatenating (a means of combining) your files allows them to be transferred much more quickly and efficiently, which can greatly improve the user experience and performance of your website.


CSS

How is CSS minified?

CSS is minified in 3 main ways:

By doing this, the size of a CSS file can easily shrink by 20%, sometimes more.

How to minify your CSS

The most sensible and maintainable way to minify your CSS is by using some sort of automated task, usually through a task runner like Gulp or Grunt. These allow you to "watch" files for changes, and automatically minify your CSS into a separate file whenever that file changes. You then point to the minfied file in your HTML (not the original), allowing you to always have a copy of both your original working CSS, and the minified production copy. Popular CSS minifiers include gulp-cssmin and grunt-css.

If for whatever reason you can't or don't want to use a task runner, there are also a number of copy/paste online CSS minifiers available. Just be sure to save your original formatted CSS in case you need to make changes later.

How to concatenate your CSS files

As above, a task runner is the optimal way to concatenate your CSS files as this will allow you to automatically concatenate files in a particular order, and then load those into your HTML document. This can be done with gulp-concat-css or grunt-concat-css.


JavaScript

How is JavaScript minified?

For the most part JavaScript minification just involves stripping out whitespace, new lines and comments, however certain shorthand techniques may also be utilised where applicable.

How to minify your JavaScript?

As with CSS, the most sensible and maintainable way to minify your JavaScript is using an automated task runner like Gulp or Grunt, specifically gulp-uglify or grunt-contrib-uglify.

If you can't or don't want to use a task runner, there are online JavaScript minifiers available. Be sure to save the original formatted JavaScript so that you can make changes later.

How to concatenate your JavaScript files

Once again, a task runner is the optimal way to concatenate your JavaScript files for ease of use and maintainability. This can be done with gulp-concat or grunt-contrib-concat.


Hopefully this article has helped you get to grips with the basics of CSS and JavaScript minification and concatenation. Happy compressing!

  Back to Website Launch Checklist