最新消息:

把JS文件用gzip 压缩后,HTTP服务器的设置

http admin 5401浏览 0评论

下载 gzip for Windows

把原有的js文件通过gzip程序压缩成gz文件后,文件体积能够立马瘦下来。比如71K的jquery.js,压缩成jquery.gzjs 只有24K 整整少了2倍,2倍啊,有木有。

附件中的gzip.exe  操作方法, gzip.exe xxx.js    xxx.js 为JS文件,执行后会在当前目录多一个xxx.js.gz  用winrar 打开,可以看到xxx.js 在压缩包里面,然后把xxx.js.gz 改名为 xxx.gzjs

Nginx

nginx.conf

location ~* ^.+.gzjs$ {
add_header Content-Encoding gzip;
gzip off;
}

mime.types

application/x-javascript js gzjs;

Apache

httpd.conf

添加:

AddEncoding x-gzip .gzjs

如果Apache 网站根目录.htaccess可用的话,可以在根目录放置.htaccess文件

内容为

AddEncoding gzip .gzjs

Tomcat

web.xml

<filter>
<filter-name>GzipJsFilter</filter-name>
<filter-class>net.util.GzipJsFilter</filter-class>
<init-param>
<param-name>headers</param-name>
<param-value>Content-Encoding=gzip</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>GzipJsFilter</filter-name>
<url-pattern>*.gzjs</url-pattern>
</filter-mapping>

package net.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GzipJsFilter
implements Filter
{
Map headers = new HashMap();

public void destroy() { }

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)

throws IOException, ServletException {
if (req instanceof HttpServletRequest)
doFilter((HttpServletRequest)req, (HttpServletResponse)res, chain);
else
chain.doFilter(req, res);
}

public void doFilter(HttpServletRequest request, HttpServletResponse response,

FilterChain chain)
throws IOException, ServletException
{
request.setCharacterEncoding(“UTF-8″);
for (Iterator it = this.headers.entrySet().iterator(); it.hasNext(); ) {
Map.Entry entry = (Map.Entry)it.next();
response.addHeader((String)entry.getKey(), (String)entry.getValue());
}
chain.doFilter(request, response);
}

public void init(FilterConfig config) throws ServletException {
String headersStr = config.getInitParameter(“headers”);
String[] headers = headersStr.split(“,”);
for (int i = 0; i < headers.length; ++i) {
String[] temp = headers[i].split(“=”);
this.headers.put(temp[0].trim(), temp[1].trim());
}
}
}

IIS

Internet信息服务(IIS)管理器,右击”网站”->”属性”,打开”服务”选项卡。在”HTTP压缩”框中选中”压缩应用程序文件”和”压缩静态文件”
IIS6/7/8 估计还要设置下 文件头 application/x-gzip .gzjs

如果服务器不支持GZIP设置,而你又想体验下gzjs的快感。有变通的办法可以实现

PHP例子

<?php

header(‘Content-Encoding: gzip’);

echo file_get_contents(‘jquery.ui.gzjs’);

?>

其他语言可以变通下,其实在输出文件时先输出头部信息Content-Encoding: gzip

转载请注明:爱开源 » 把JS文件用gzip 压缩后,HTTP服务器的设置

您必须 登录 才能发表评论!