启用文件压缩


第一部分 – 第07章

Document

当用户访问移动网站页面时,会向网站服务器发送对该页面的http请求网站服务器将向发送请求的网络浏览器返回http响应(例如页面数据)。每个响应都会占用一定量的文件大小。

当http响应的文件大小(例如你的网站页面的数据文件大小)被减少时,由于需要从你的网站服务器传输到用户的网络浏览器的数据包更少,响应传输的时间就减少了。以这样的方式,用户可以更快地通过网络浏览器加载移动网站页面。

减少数据文件大小

为了减少数据文件大小,你应该启用文件压缩。

  • Gzip压缩是一个经典的文件压缩方法,它可以将你的HTML和CSS文件压缩到更小。
  • 已压缩文件的大小可能会明显小一些。在某些情况下,已压缩文件的大小可能比原始大小要小50%。

压缩是如何运行的

假定你的HTML和CSS文件已经被压缩了。为了在网络浏览器和你的网站服务器之间文件压缩得以运行:

  • 你必须通过你的网站服务器配置启用Gzip压缩。假设你的移动网站使用的是Apache或者Nginx作为网站服务器。

当网络浏览器(支持Gzip压缩)从你的移动网站请求页面时,你的网站服务器将返回压缩过的文件。

为Apache启用Gzip压缩

Apache有两个选项用于启用Gzip压缩:

  • mod_deflate:这是标准方式,且设置简易。
  • mod_gzip:这种方式更为强大,允许内容预压缩,但是这种方式设置起来更为复杂。

为了在Apache上启用Gzip压缩,应将如下代码添加至.htaccess文件。

<IfModule mod_deflate.c>
# Compress HTML, CSS, JavaScript, Text, XML and fonts
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml
  
# Remove browser bugs for really old browsers
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4\.0[678] no-gzip
  BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
  Header append Vary User-Agent
</IfModule>

为Nginx启用Gzip压缩

为了在Nginx上启用Gzip压缩,应将如下代码添加至config文件。

gzip on;
gzip_comp_level 2;
gzip_http_version 1.0;
gzip_proxied any;
gzip_min_length 1100;
gzip_buffers 16 8k;
gzip_types text/plain text/html text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;

# Disable for IE < 6 because there are some known problems
gzip_disable "MSIE [1-6].(?!.*SV1)";

# Add a vary header for downstream proxies to avoid sending cached gzipped files to IE6
gzip_vary on;


移动网站性能技术白皮书在2017年3月正式出版。

英文版:Enable File Compression – 繁体中文版:启用文件压缩







移动网站性能技术白皮书上的内容按下列许可协议发布: CC Attribution-Noncommercial 4.0 International

Gordon Choi's Mobile Website Book