当前位置:编程学习 > JS >>

web优化之-Asp.net MVC js、css动态合并 动态压缩

上次写了两篇有关js的合并压缩如
web优化之-mvc js动态合并 动态压缩 去掉js重复引用 js缓存 js延迟加载
web优化之-asp.net js延迟加载 js动态合并 js动态压缩
看了一下的访问两比较大,现在js和css的合并压缩整理一下。

首先还是需要一个handler来处理文件的合并、压缩、缓存,.js和css的压缩我们采用的是Yahoo.Yui.Compressor,所以需要引用Yahoo.Yui.Compressor.dll文件

代码如下:


[csharp] view plaincopyprint?public class CombineFiles : IHttpHandler 
   { 
 
       public void ProcessRequest(HttpContext context) 
       { 
           context.Response.ContentType = "text/javascript"; 
           HttpRequest request = context.Request; 
           HttpResponse response = context.Response; 
           string[] allkeys = request.QueryString.AllKeys; 
           if (!allkeys.Contains("href") || !allkeys.Contains("type") || !allkeys.Contains("compress")) 
           { 
               response.Write("请求格式不正确,正确格式是type=....&href=....&compress=..."); 
               response.Write("type只能是js或则css,compress只能是true或则false,href则是请求的文件,多个文件已逗号分隔"); 
           } 
           else 
           { 
               string cacheKey = request.Url.Query; 
               #region /*确定合并文件类型*/  
               string fileType = request.QueryString["type"].Trim().ToLower(); 
               string contenType = string.Empty; 
               if (fileType.Equals("js")) 
               { 
                   contenType = "text/javascript"; 
               } 
               else if (fileType.Equals("css")) 
               { 
                   contenType = "text/css"; 
               } 
               /*确定合并文件类型*/
               #endregion  
               CacheItem cacheItem = HttpRuntime.Cache.Get(cacheKey) as CacheItem;//服务端缓存  
               if (cacheItem == null) 
               { 
                   #region 合并压缩文件  
                   /*合并文件*/ 
                   string href = context.Request.QueryString["href"].Trim(); 
                   string content = string.Empty; 
                   string[] files = href.Split(new string[] { ",", "," }, StringSplitOptions.RemoveEmptyEntries); 
                   StringBuilder sb = new StringBuilder(); 
                   foreach (string fileName in files) 
                   { 
                       string filePath = context.Server.MapPath(fileName); 
                       if (File.Exists(filePath)) 
                       { 
                           string readstr = File.ReadAllText(filePath, Encoding.UTF8); 
                           sb.Append(readstr); 
                           //content = JavaScriptCompressor.Compress(content);  
                           //response.Write(content);  
                       } 
                       else 
                       { 
                           sb.AppendLine("\r\n未找到源文件" + filePath + "\r\n"); 
                       } 
                   } 
                   content = sb.ToStri

补充:Web开发 , ASP.Net ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,