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     }

最后在配置文件中配置一下CombineFiles.axd文件,具体配置略

 

引用如下

 <script type="text/javascript" src="/js/CombineFiles.axd?type=js"></script>
 <link rel="stylesheet" type="text/css" href="/css/CombineFiles.axd?type=css" />

 

 

 

转载于:https://www.cnblogs.com/benwu/archive/2012/11/09/2762857.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值