Combine and Minify Multiple CSS / JS Files
Asked Answered
C

12

102

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.

Coraciiform answered 15/2, 2012 at 4:18 Comment(1)
I'm hoping they introduce something like this in the new asp.net 4.5 stuff so that in 'debug' the scripts are rendered individually and un-minified but in 'release' they are combined and minifiedVillatoro
C
12

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.

Coraciiform answered 27/2, 2013 at 19:1 Comment(2)
this is just for mac...wht abt windows??Issuance
I use CodeKit and love it... except that checking out a project to a new branch with git kills my js concatenations. Going to start using npm.Selfrevealing
W
35

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

Woodenware answered 15/2, 2012 at 4:21 Comment(1)
Hi Noodles, Its not working for me. It gives me 404 for that script src. i used - <script src="test.com/script1.js,http://test.com/script2.js"></…> and all js files giving loading errorsTabling
D
28

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: (updated 6th of March, 2023)

So now people use yarn to run npm. No wonder; yarns icon is a cat.

Most current frameworks use something like webpack or vite to bundle the resources into packages, which then also takes care of minification.

If you still need to do this by hand, you should at least use something like yarn or npm as a runner and then choose a tool like minify and maybe combine-files.

Decorum answered 21/2, 2012 at 12:3 Comment(6)
from the link above At the moment it does not have support for minimising CSS files even though this is a feature of YUI Compressor.Enswathe
Well on the YUI Compressor website it reads: "The YUI Compressor is also able to compress CSS files by using a port of Isaac Schlueter's regular-expression-based CSS minifier." Also: yui.github.io/yuicompressor/css.htmlDecorum
Great history of workflow solutions, and look forward to the next update!Selfrevealing
ANY UPDATE ? What do people do nowadays ?Englishism
@Xsmael: I added a more current UpdateDecorum
I once again updated this post for those still in need to minify by handDecorum
O
19

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.

Obi answered 27/2, 2012 at 6:27 Comment(0)
S
14

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
Sporting answered 1/4, 2016 at 10:55 Comment(1)
The simplest method/concept I've found that should work perfectly even though I'm using a different language altogether. My idea now is to turn it into a cache file of sorts and have the page call to it. Thanks.Connivance
C
12

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.

Coraciiform answered 27/2, 2013 at 19:1 Comment(2)
this is just for mac...wht abt windows??Issuance
I use CodeKit and love it... except that checking out a project to a new branch with git kills my js concatenations. Going to start using npm.Selfrevealing
G
10

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

Gilbertgilberta answered 1/2, 2015 at 20:13 Comment(0)
B
6

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.

Burkhalter answered 27/2, 2012 at 21:26 Comment(0)
V
6

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.

Vadnee answered 7/9, 2013 at 17:33 Comment(0)
B
4

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

3) 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!

Backdate answered 26/9, 2014 at 23:18 Comment(0)
S
3

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.

Shutter answered 27/2, 2012 at 23:28 Comment(0)
M
1

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.

Matrilocal answered 25/1, 2015 at 18:26 Comment(0)
P
1

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);
Pliny answered 29/1, 2016 at 19:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.