Asp.net 程序优化js,css合并与压缩

访问时将js和css压缩并且缓存在客户端,
采用的是Yahoo.Yui.Compressor组件还完成的,从这里可下载

创建一个IHttpHandler来处理文件

 

复制代码
  1  public  class CombineFiles : IHttpHandler
  2     {
  3          private  const  string CacheKeyFormat =  " _CacheKey_{0}_ ";
  4 
  5          private  const  bool IsCompress =  true// 需要压缩
  6 
  7          public  bool IsReusable
  8         {
  9              get
 10             {
 11                  return  false;
 12             }
 13         }
 14 
 15          public  void ProcessRequest(HttpContext context)
 16         {
 17             HttpRequest request = context.Request;
 18             HttpResponse response = context.Response;
 19 
 20              string cachekey =  string.Empty;
 21 
 22              string type = request.QueryString[ " type "];
 23              if (! string.IsNullOrEmpty(type) && (type ==  " css " || type ==  " js "))
 24             {
 25                  if (type ==  " js ")
 26                 {
 27                     response.ContentType =  " text/javascript ";
 28 
 29                 }
 30                  else  if (type ==  " css ")
 31                 {
 32                     response.ContentType =  " text/css ";
 33                 }
 34 
 35                 cachekey =  string.Format(CacheKeyFormat, type);
 36 
 37                 CompressCacheItem cacheItem = HttpRuntime.Cache[ cachekeyas CompressCacheItem;
 38                  if (cacheItem ==  null)
 39                 {
 40                      string content =  string.Empty;
 41                      string path = context.Server.MapPath( "");
 42                      // 找到这个目录下所有的js或css文件,当然也可以进行配置,需求请求压缩哪些文件
 43                       // 这里就将所的有文件都请求压缩
 44                      string[] files = Directory.GetFiles(path,  " *. " + type);
 45                     StringBuilder sb =  new StringBuilder();
 46                      foreach ( string fileName  in files)
 47                     {
 48                          if (File.Exists(fileName))
 49                         {
 50                              string readstr = File.ReadAllText(fileName, Encoding.UTF8);
 51                             sb.Append(readstr);
 52                         }
 53                     }
 54 
 55                     content = sb.ToString();
 56 
 57                      //  开始压缩文件
 58                      if (IsCompress)
 59                     {
 60                          if (type.Equals( " js "))
 61                         {
 62                              content = JavaScriptCompressor.Compress(content);
 63                         }
 64                          else  if (type.Equals( " css "))
 65                         {
 66                              content = CssCompressor.Compress(content);
 67                         }
 68                     }
 69 
 70                      // 输入到客户端还可以进行Gzip压缩 ,这里就省略了
 71 
 72                     cacheItem =  new CompressCacheItem() { Type = type, Content = content, Expires = DateTime.Now.AddDays( 30) };
 73                     HttpRuntime.Cache.Insert(cachekey, cacheItem,  null, cacheItem.Expires, TimeSpan.Zero);
 74                 }
 75 
 76                  string ifModifiedSince = request.Headers[ " If-Modified-Since "];
 77                  if (! string.IsNullOrEmpty(ifModifiedSince)
 78                     && TimeSpan.FromTicks(cacheItem.Expires.Ticks - DateTime.Parse(ifModifiedSince).Ticks).Seconds <  0)
 79                 {
 80                     response.StatusCode = ( int)System.Net.HttpStatusCode.NotModified;
 81                     response.StatusDescription =  " Not Modified ";
 82                 }
 83                  else
 84                 {
 85                     response.Write(cacheItem.Content);
 86                     SetClientCaching(response, cacheItem.Expires);
 87                 }
 88             }
 89 
 90         }
 91 
 92          private  void SetClientCaching(HttpResponse response, DateTime expires)
 93         {
 94             response.Cache.SetETag(DateTime.Now.Ticks.ToString());
 95             response.Cache.SetLastModified(DateTime.Now);
 96 
 97              // public 以指定响应能由客户端和共享(代理)缓存进行缓存。    
 98             response.Cache.SetCacheability(HttpCacheability.Public);
 99 
100              // 是允许文档在被视为陈旧之前存在的最长绝对时间。 
101             response.Cache.SetMaxAge(TimeSpan.FromTicks(expires.Ticks));
102 
103             response.Cache.SetSlidingExpiration( true);
104         }
105          private  class CompressCacheItem
106         {
107              ///   <summary>
108               ///  类型 js 或 css 
109               ///   </summary>
110              public  string Type {  getset; }  //  js css  
111              ///   <summary>
112               ///  内容
113               ///   </summary>
114              public  string Content {  setget; }
115              ///   <summary>
116               ///  过期时间
117               ///   </summary>
118              public DateTime Expires {  setget; }
119         }
120     }
复制代码
 http://www.cnblogs.com/benwu/archive/2012/11/09/2762857.html

你可能感兴趣的:(asp.net)