YAOHAIXIAO.COM

HTML(5),CSS(3),JavaScript,DOM,Ajax,JSON,Front-end technologies & Yaohaixiao

热门标签:JavaScript Performance 前端开发 前端性能优化 原创

Rss

Home » Frontend » Performance » 前端性能优化:Minify JavaScript and CSS

前端性能优化:Minify JavaScript and CSS

今天要介绍的YSlow的前端性能优化规则是 Minify JavaScript and CSS(压缩JavaScriptCSS)。

为什么要压缩JavaScriptCSS

为什么要压缩 JavaScriptCSS?这个问题很好解答,因为压缩了JavaScriptCSS代码后,文件大小就会降低,文件的下载速度就更快,页面也就可以更快的呈现出来。

压缩了哪些内容

Minification is the practice of removing unnecessary characters from code to reduce its size thereby improving load times. When code is minified all comments are removed, as well as unneeded white space characters (space, newline, and tab). In the case of JavaScript, this improves response time performance because the size of the downloaded file is reduced. Two popular tools for minifying JavaScript code are JSMin and YUI Compressor. The YUI compressor can also minify CSS.

我们前面介绍过GZip压缩,GZip压缩的只是使用GZip特殊的压缩算法将整个文件进行了“粗线条”的压缩。而我们这里的 Minify JavaScript and CSS,则更加细化。通过去掉 JavaScriptCSS 代码中不必要的空格、回车、换行等字符,以及使用简单字母替换长的变量名等方式,更加精细的处理来压缩代码。这些处理是Gzip压缩做不到。

In addition to minifying external scripts and styles, inlined <script> and <style> blocks can and should also be minified. Even if you gzip your scripts and styles, minifying them will still reduce the size by 5% or more. As the use and size of JavaScript and CSS increases, so will the savings gained by minifying your code.

我们不仅要压缩外部调用的JavaScriptCSS文件,同时也要压缩写在HTML代码内,在 <script> 和 <style> 标签中的代码片段。

压缩的方式

Obfuscation is an alternative optimization that can be applied to source code. It’s more complex than minification and thus more likely to generate bugs as a result of the obfuscation step itself. In a survey of ten top U.S. web sites, minification achieved a 21% size reduction versus 25% for obfuscation. Although obfuscation has a higher size reduction, minifying JavaScript is less risky.

通常我们有 MinificationObfuscation 压缩方式。Obfuscation 的压缩比要略高于 Minification。但是 Obfuscation 压缩JavaScript时比较容易出现问题,所以通常我们都采用 Minification 方式压缩代码,毕竟代码的稳定性比起那差别不大的压缩比还是更为重要一些。

两种方式的具体比较大家看看 Douglas Crockford 的 《Minification v Obfuscation》这篇文章。

压缩JavaScriptCSS代码的工具

压缩JavaScriptCSS代码的工具有很多,具体的大家可以看看《隐藏 JavaScript 源代码?不,你只能混淆和压缩JavaScript源代码》一文中介绍的工具。我这里就给出一些工具的列表:

声明:本文采用BY-NC-SA协议进行授权。转载请注明转自:前端性能优化:Minify JavaScript and CSS

« »

发表评论

电子邮件地址不会被公开。 必填项已用*标注

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(Spamcheck Enabled)