合并和缩小多个 CSS/JS 文件

我试图通过合并和压缩 CSS 和 JS 文件来优化站点性能。我的问题更多的是关于如何实现这个目标的(具体的)步骤,考虑到我所面临的一个实际情况(尽管在其他开发人员中也应该是典型的)。

我的页面引用了几个 CSS 和 JS 文件,如下所示:

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

对于产品发行版,我想将3个 CSS 文件合并成一个,并使用例如 YUI 压缩机对其进行缩小。但是,我需要更新所有需要这3个文件来引用新缩小的 CSS 的页面。这似乎很容易出错(例如,在许多文件中删除并添加一些行)。还有其他低风险的方法吗?对于 JS 文件也是同样的问题。

186988 次浏览

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

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.

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.

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.

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.

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.

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.

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!

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.

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

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

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