Asp.net程序优化js、css实现合并与压缩的方法
本文实例讲述了Asp.net程序优化js、css实现合并与压缩的方法。分享给大家供大家参考。具体实现方法如下:
访问时将js和css压缩并且缓存在客户端,
采用的是Yahoo.Yui.Compressor组件来完成的,用户可以点击此处本站下载。
创建一个IHttpHandler来处理文件
publicclassCombineFiles:IHttpHandler { privateconststringCacheKeyFormat="_CacheKey_{0}_";
privateconstboolIsCompress=true;//需要压缩
publicboolIsReusable { get { returnfalse; } }
publicvoidProcessRequest(HttpContextcontext) { HttpRequestrequest=context.Request; HttpResponseresponse=context.Response;
stringcachekey=string.Empty;
stringtype=request.QueryString["type"]; if(!string.IsNullOrEmpty(type)&&(type=="css"||type=="js")) { if(type=="js") { response.ContentType="text/javascript";
} elseif(type=="css") { response.ContentType="text/css"; }
cachekey=string.Format(CacheKeyFormat,type);
CompressCacheItemcacheItem=HttpRuntime.Cache[cachekey]asCompressCacheItem; if(cacheItem==null) { stringcontent=string.Empty; stringpath=context.Server.MapPath(""); //找到这个目录下所有的js或css文件,当然也可以进行配置,需求请求压缩哪些文件 //这里就将所的有文件都请求压缩 string[]files=Directory.GetFiles(path,"*."+type); StringBuildersb=newStringBuilder(); foreach(stringfileNameinfiles) { if(File.Exists(fileName)) { stringreadstr=File.ReadAllText(fileName,Encoding.UTF8); sb.Append(readstr); } }
content=sb.ToString();
//开始压缩文件 if(IsCompress) { if(type.Equals("js")) { content=JavaScriptCompressor.Compress(content); } elseif(type.Equals("css")) { content=CssCompressor.Compress(content); } }
//输入到客户端还可以进行Gzip压缩,这里就省略了
cacheItem=newCompressCacheItem(){Type=type,Content=content,Expires=DateTime.Now.AddDays(30)}; HttpRuntime.Cache.Insert(cachekey,cacheItem,null,cacheItem.Expires,TimeSpan.Zero); }
stringifModifiedSince=request.Headers["If-Modified-Since"]; if(!string.IsNullOrEmpty(ifModifiedSince) &&TimeSpan.FromTicks(cacheItem.Expires.Ticks-DateTime.Parse(ifModifiedSince).Ticks).Seconds<0) { response.StatusCode=(int)System.Net.HttpStatusCode.NotModified; response.StatusDescription="NotModified"; } else { response.Write(cacheItem.Content); SetClientCaching(response,cacheItem.Expires); } } }
privatevoidSetClientCaching(HttpResponseresponse,DateTimeexpires) { response.Cache.SetETag(DateTime.Now.Ticks.ToString()); response.Cache.SetLastModified(DateTime.Now);
//public以指定响应能由客户端和共享(代理)缓存进行缓存。 response.Cache.SetCacheability(HttpCacheability.Public);
//是允许文档在被视为陈旧之前存在的最长绝对时间。 response.Cache.SetMaxAge(TimeSpan.FromTicks(expires.Ticks));
response.Cache.SetSlidingExpiration(true); } privateclassCompressCacheItem { ///<summary> ///类型js或css ///</summary> publicstringType{get;set;}//jscss ///<summary> ///内容 ///</summary> publicstringContent{set;get;} ///<summary> ///过期时间 ///</summary> publicDateTimeExpires{set;get;} } }