Combine and Minify Multiple CSS / JS Files

JavascriptCssOptimizationYui CompressorHttp Compression

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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.

Solution 3 - Javascript

>I'd need to update all pages that needs these 3 files to reference to the newly-minified CSS.

Firstly I would say you should have common header. So it will needn't to change all headers at all time whenever necessary. It's good practice to have single header or 2-3. So as your page need you can change your header. So whenever you want to extend your web-app it will be less risky and tedious.

You havn't mentioned your development environments. You can see there are many compressing tools listed for different environments. And you are using good tool i.e.YUI Compressor.

Solution 4 - Javascript

Quick tip for windows users, if you only want to concat files:

Open a cmd at the desired place, and just pipe your files to a file using "type"

ex:

type .\scripts\*.js >> .\combined.js

If the order of your scripts is important, you have to explicitly type the files, in the desired order.

I use this in a bat file for my angular/bootstrap projects

del combos.js

type .\lib\jquery.min.js >> .\combos.js
type .\lib\bootstrap.min.js >> .\combos.js
type .\lib\Angular\angular.min.js >> .\combos.js
type .\lib\Angular\angular-route.min.js >> .\combos.js
type .\lib\Angular\angular-sanitize.min.js >> .\combos.js

type .\app.js >> .\combos.js
type .\services\*.js >> .\combos.js
type .\controllers\*.js >> .\combos.js

Solution 5 - Javascript

I ended up using CodeKit to concatenate my CSS and JS files. The feature that I find really useful is the ability to do the concatenation upon file save; because it monitors the respective CSS / JS assets. Once I got them properly combined e.g. to 1 CSS and 1 JS files, all other files simply can refer to these 2.

You can even ask CodeKit to do on-the-fly minification / compression.

Disclaimer: I am not affiliated in any way with CodeKit. I randomly found it on the web and it has served as a great tool in my development process. It also comes with good updates since I first used it more than a year ago.

Solution 6 - Javascript

It's 2015 year in the street and the easiest way imo is using gulp - http://gulpjs.com/. Minifying code using gulp-uglify for js scripts and gulp-minify-css for css is very simple. Gulp is definitely worth of trying

Solution 7 - Javascript

I dont see you mention a content management system (Wordpress, Joomla, Drupal, etc) but if you are using any popular CMS they all have plugins/modules available (free options as well) that will minify and cache your css and js.

Using a plugin gives you the ability to keep the uncompressed versions available for editing, then when changes are made the plugin automatically includes your changes and re compresses the file. Just make sure you choose a plugin that will let you exclude files (such as a custom js file) incase it breaks anything.

I have tried in the past to keep these files up manually and it always turns into a maintenance nightmare. Good luck, hope this helped.

Solution 8 - Javascript

For people who want something a little more lightweight and flexible, I created js.sh today to address this problem. It's a simple command line tool targeted toward JS files that could easily be modified to take care of CSS files too. Benefits:

  • Easily configurable for use by multiple developers on a project
  • Combines JS files in the order specified in script_order.txt
  • Compresses them with Google's Closure Compiler
  • Splits JS into <25kb chunks where possible since the iPhone won't cache anything greater than 25kb
  • Generates a small PHP file with <script> tags that you can include where appropriate
  • Usage: js.sh -u yourname

It could use some improvements, but it's better for my use case than all of the other solutions I've seen so far.

Solution 9 - Javascript

First step of optimization is file minimization. (I strongly recommend GULP for minimization and optimization. Its simple watch solution, installation and all files are compressed at once.Supports all CSS, JS,less, sass, etc...)

OR Old school solution:

  1. In general, as a process of optimization, to optimize a site performance, try merging all CSS in one file and compress file by using Compass. That way your multiple requests to static CSS will be replaced with single one.

  2. Problem of multiple JS you can resolve by using CDN (or Google Hosted Libraries) so requests go to other server not yours. That way server doesn't wait for previous request to complete before sending next.

  3. If you have your own locally stored JavaScript minimize each file by using Brackets plugin "Compress JavaScript". It's basically one click to compress JavsScript.Brackets is free editor made for CSS and JS but can be used for PHP and other languages. There is plenty of plugins to choose made for both front-end and back-end developers. In general "one click" to do all these (so far multiple) commands. Btw, Brackets replaced my very expensive Dreamweaver ;)

  4. Try using tools like Sass, Compass, less to minimize you CSS.

Note: Even without using SASS mixing or variables your CSS will be compressed (just simple use pure CSS and Compass "watch" command will compress it for you).

I hope this helps!

Solution 10 - Javascript

If you're doing any pre-processing on the files you serve, you probably want to set up a proper build system (eg a Makefile). That way, you have some source files with no duplication, and whenever you make a change, you run 'make' and it brings all the automatically-generated files up to date. If there is already a build system in place, learn how it works and use it. If not, you'll need to add one.

So first, figure out how to combine and minify your files from the command line (the YUICompressor documentation covers this). Designate a directory for automatically-generated stuff, separate from the stuff you work on but accessible to the web server, and output to there, eg gen/scripts/combined.js. Put the commands you used into a Makefile, and rerun 'make' every time you've made a change and want it to take effect. Then update the headers in other files to point to the combined and minified files.

Solution 11 - Javascript

In my symfony project I do something like this

{# layout.html.twig #}

{% block styles %}
    {% if app.environment == 'prod' %}
        <link href="{{ asset('bundles/appmain/min.css') }}" rel="stylesheet" type="text/css" />
    {% else %}
        <link href="{{ asset('bundles/appmain/hello.css') }}" rel="stylesheet" type="text/css" />
        <link href="{{ asset('bundles/appmain/world.css') }}" rel="stylesheet" type="text/css" />
    {% endif %}
{% endblock %}

{# some-view.html.twig #}

{% extends 'AppMainBundle::layout.html.twig' %}

{% block styles %}
    {{ parent() }}

    {% if app.environment != 'prod' %}
        <link href="{{ asset('bundles/appsecond/styles.css') }}" rel="stylesheet" type="text/css" />
    {% else %}
{% endblock %}

When the dev version is ready for production, I use this script to combine all css files and replace the contents of min.css.

But this solution works only if the same css files are included in all pages.

Solution 12 - Javascript

You can use the cssmin node module which is built from the famous YUI compressor

$ npm -g i cosmic # install

# Usage   
var puts = require('util').puts,
fs = require('fs'),
cssmin = require('./cssmin');
var css = fs.readFileSync("/Any/Random/CSS/File.css", encoding='utf8');
var min = cssmin(css);
puts(min);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmoeyView Question on Stackoverflow
Solution 1 - JavascriptNoodlesView Answer on Stackoverflow
Solution 2 - JavascriptAndresch SerjView Answer on Stackoverflow
Solution 3 - JavascriptSomnath MulukView Answer on Stackoverflow
Solution 4 - JavascriptmpxView Answer on Stackoverflow
Solution 5 - JavascriptmoeyView Answer on Stackoverflow
Solution 6 - JavascriptigolkotekView Answer on Stackoverflow
Solution 7 - JavascriptRachelDView Answer on Stackoverflow
Solution 8 - JavascriptBen YView Answer on Stackoverflow
Solution 9 - JavascriptStefaDesignView Answer on Stackoverflow
Solution 10 - JavascriptjimrandomhView Answer on Stackoverflow
Solution 11 - JavascriptmoldcraftView Answer on Stackoverflow
Solution 12 - JavascriptsdcView Answer on Stackoverflow