Minify And Compress Javascript And Css

Minify And Compress Javascript And Css

服务端如何压缩网页中的JS和CSS文件?
http://blog.163.com/bavol_cai/blog/static/16679074020106561719560/

2010-07-05

To optimize the Web, minimizing the http request is a important task.(YSlow rule).

  • Merge JavaScript
  • Merge CSS
  • CSS Sprites (popular)
  • Image Map
  • encoding image with Data URI (not support by IE6 and IE7, not popular)

Merge JavaScript, Merge CSS are very heavy task and not easy to control, this article is addressing this topic.

YUI Combo Handler

Combo Handler is a Apache module developed by Yahoo!, to merge js and css file.
Example:

YUI2 Rich Text Editor import JavaScript files with classic method:

<script src="http://yui.yahooapis.com/2.8.0r4/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script src="http://yui.yahooapis.com/2.8.0r4/build/container/container_core-min.js"></script>
<script src="http://yui.yahooapis.com/2.8.0r4/build/menu/menu-min.js"></script>
<script src="http://yui.yahooapis.com/2.8.0r4/build/element/element-min.js"></script>
<script src="http://yui.yahooapis.com/2.8.0r4/build/button/button-min.js"></script>
<script src="http://yui.yahooapis.com/2.8.0r4/build/editor/editor-min.js"></script>

With Combo Handler:

<script src="http://yui.yahooapis.com/combo?
2.8.0r4/build/yahoo-dom-event/yahoo-dom-event.js&
2.8.0r4/build/container/container_core-min.js&
2.8.0r4/build/menu/menu-min.js&
2.8.0r4/build/element/element-min.js&
2.8.0r4/build/button/button-min.js&
2.8.0r4/build/editor/editor-min.js"></script>

YUI from 2.6.0, have YUI Loader embedded with Combo Handling. Only set combine attribute to true, loader will combine multiple js from Yahoo! CDN(http://yui.yahooapis.com).

Minify

Minify is a PHP OSS project hosted by google, which combine, simplify, gzip compress and cache java and css files.
Example: Rich Text Editor import

<script src="http://yui.yahooapis.com/min/f=
2.8.0r4/build/yahoo-dom-event/yahoo-dom-event.js,
2.8.0r4/build/container/container_core-min.js,
2.8.0r4/build/menu/menu-min.js,
2.8.0r4/build/element/element-min.js,
2.8.0r4/build/button/button-min.js,
2.8.0r4/build/editor/editor-min.js"></script>

Setup Minify

Install Apache + PHP (Windows, Mac)

copy min dir to root dir, i.e. localhost and minify url will be http://localhost/min/f=
enable Apache Mod Rewrite, create .htaccess under min dir and add the following Rewrite rule:
<IfModule mod_rewrite.c>
RewriteEngine on

  1. You may need RewriteBase on some servers
  2. if it doesn't work try the following

#RewriteBase /min

  1. rewrite URLs like "/min/f=…" to "/min/?f=…"

RewriteRule ^([bfg]=.*) index.php?$1 [L,NE]
</IfModule>

without rewrite, url will be http://localhost/min/index.php?f= will cause cache problem.
with rewrite url will be http://localhost/min/f=

configure Minify - edit min/config.php

use Minify on cdn

See Also:
minify-and-compress-javascript-and-css