Combine and Minify Multiple CSS / JS Files


I am trying to optimize a site performance by consolidating and compressing the CSS and JS files. My question is more about the (concrete) steps on how to achieve this, given a real situation I was facing (should be typical among other developers too, though).

My page references several CSS and JS files like the following:

  It's easier to work on smaller files during development.
  Hence, the multiple CSS and JS files.
<link type="text/css" rel="stylesheet" href="/css/main.css" />
<link type="text/css" rel="stylesheet" href="/css/secondary-1.css" />
<link type="text/css" rel="stylesheet" href="/css/secondary-2.css" />

<script type="text/javascript" src="/scripts/js/main.js"></script>
<script type="text/javascript" src="/scripts/js/adapter/adapter.js"></script>
<script type="text/javascript" src="/scripts/js/adapter/title-adapter.js"></script>

For the production release, I'd like to combine the 3 CSS files into one and minify it using e.g. YUI Compressor. But then, I'd need to update all pages that needs these 3 files to reference to the newly-minified CSS. This seems error-prone (e.g. you're removing and adding some lines in many files). Any other less-risky approach? The same issue for the JS files.

This question is tagged with javascript css optimization yui-compressor http-compression

~ Asked on 2012-02-15 04:18:07

The Best Answer is


Check out minify - it allows you combine multiple js, css files into one just by stacking them into a url, e.g.

<script src="/scripts/js/main.js,/scripts/js/adapter/adapter.js"></script>

We've used it for years and it does a great job and does it on the fly (no need to edit files).

~ Answered on 2012-02-15 04:21:34


I think the YUI Compressor is the best there is. It minifies JS and CSS and it even strips those console.log statements people use for low-level JavaScript debugging.

Check out how easy it is.

You can start it in an ant task and therefore include it into your post/pre-commit hooks if you use svn/git.

UPDATE: Nowadays I use grunt with the concat, minify & uglify contributions. You can use it with a watcher so it creates new minified files in the background whenever you change your source. The uglify contrib not only strips console logs, but it also strips unused functions and properties.

See this tutorial for a brief insight.

UPDATE: Nowadays people step back from grunt und its predecessor "gulp" and use npm as a build tool. Read up on it here.

UPDATE: So now people use yarn to run npm. No wonder; yarns icon is a cat. Most current frameworks use webpack to bundle the resources into packages, which then also takes care of minification.

~ Answered on 2012-02-21 12:03:45

Most Viewed Questions: