本文实例讲述了Asp.net程序优化js、css实现合并与压缩的方法。。具体实现方法如下:
访问时将js和css压缩并且缓存在客户端,
采用的是Yahoo.Yui.Compressor组件来完成的,用户可以点击此处本站下载。
创建一个IHttpHandler来处理文件
代码如下:
public class CombineFiles : IHttpHandler
{
private const string CacheKeyFormat = "_CacheKey_{0}_";
private const bool IsCompress = true; //需要压缩
public bool IsReusable
{
get
{
return false;
}
}
public void ProcessRequest(HttpContext context)
{
HttpRequest request = context.Request;
HttpResponse response = context.Response;
string cachekey = string.Empty;
string type = request.QueryString["type"];
if (!string.IsNullOrEmpty(type) && (type == "css" || type == "js"))
{
if (type == "js")
{
response.ContentType = "text/javascript";
}
else if (type == "css")
{
response.ContentType = "text/css";
}
cachekey = string.Format(CacheKeyFormat, type);
CompressCacheItem cacheItem = HttpRuntime.Cache[cachekey] as CompressCacheItem;
新闻热点
疑难解答
图片精选