访问时将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[cachekey] as 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() };
 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 < )
 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 
             //是允许文档在被视为陈旧之前存在的最长绝对时间。 
             response.Cache.SetMaxAge(TimeSpan.FromTicks(expires.Ticks));
 
             response.Cache.SetSlidingExpiration(true);
         }
         private class CompressCacheItem
         {
             /// <summary>
             /// 类型 js 或 css 
             /// </summary>
             public string Type { get; set; } // js css  
             /// <summary>
             /// 内容
             /// </summary>
             public string Content { set; get; }
             /// <summary>
             /// 过期时间
             /// </summary>
             public DateTime Expires { set; get; }
         }
     }  http://www.cnblogs.com/benwu/archive/2012/11/09/2762857.html

Asp.net 程序优化js,css合并与压缩的更多相关文章

  1. Google Pagespeed,自动压缩优化JS/CSS/Image

    Google Pagespeed,自动压缩优化JS/CSS/Image 浏览: 发布日期:// 分类:技术分享 关键字: Nginx Appache Pagespeed 自动压缩优化JS/CSS/Im ...

  2. js文件合并,压缩,缓存,延迟加载

    做web前段也有一段时间了,对于web中js文件的加载有些体会想跟大家一起分享一下. 1.首先说说js文件的合并和压缩吧 为了便于集中式管理js的合并和压缩我们创建一个Js.ashx文件来专门处理合并 ...

  3. Gulp学习指南之CSS合并、压缩与MD5命名及路径替换(转载)

    本文转载自: Gulp学习指南之CSS合并.压缩与MD5命名及路径替换

  4. requireJS中如何用r.js对js进行合并和压缩css文件

    我运行的环境是windows+node.js,首先是用npm安装requirejs(全局安装,即使用 'npm install requirejs -g',这样方便在各个目录调用),接着就是下载r.j ...

  5. [Asp.net Mvc]为js,css静态文件添加版本号

    方式一: 思路 string version = ViewBag.Version; @Scripts.RenderFormat("<script type=\"text/ja ...

  6. 网站优化JS css压缩

    在nginx 中开启gzip压缩后,可以大大减少资js css 体积,原来200KB,压缩后只有66KB server{ gzip on; gzip_types text/plain applicat ...

  7. gulp入坑系列(2)——初试JS代码合并与压缩

    在上一篇里成功安装了gulp到项目中,现在来测试一下gulp的合并与压缩功能 gulp入坑系列(1)--安装gulp(传送门):http://www.cnblogs.com/YuuyaRin/p/61 ...

  8. gulp学习指南之CSS合并、压缩与MD5命名及路径替换

    1.引入插件 var gulp = require('gulp'), // uglify = require('gulp-uglify'), concat = require('gulp-concat ...

  9. ASP.NET下使用Combres对JS、CSS合并和压缩

    记录一下,如何简单快捷压缩js和css,通过合并来减少请求次数. 用到的网址: http://www.nuget.org/packages/combres/ https://github.com/bu ...

随机推荐

  1. android Handlerr.removeCallbacksAndMessages(null)的妙用

    今天在阅读代码发现了android  Handlerr.removeCallbacksAndMessages(null)代码 在ondestory()调用,之前没用过,那想弄懂咋办,查api: pub ...

  2. nfs missing codepage or helper program, or other error

    [root@xxxxx ~]# /bin/mount -t nfs -o nosuid,noexec,nodev,noatime,intr,rsize=,wsize= xxx.xxx.xxx.xxx: ...

  3. You have JVM property "https.proxyHost" set to “localhost”

    Mac下Pycharm和AndroidStudio里面proxy配置页都提示这个,后来在~/.gradle/gradle.properties里面找到了proxy设置代码,删掉就好了.

  4. python super()使用详解

    1.super的作用调用父类方法2.单继承使用示例 #coding:utf-8 #单继承 class A(object): def __init__(self): self.n=2 def add(s ...

  5. MySQL常见的库操作,表操作,数据操作集锦及一些注意事项

    一 库操作(文件夹) 1 数据库命名规则 可以由字母.数字.下划线.@.#.$ 区分大小写 唯一性 不能使用关键字如 create select 不能单独使用数字 最长128位 2 数据库相关操作 创 ...

  6. Solr 数字字符不能搜索的一个问题

    问题一: 测试人员告诉我数字不能被搜索.于是开始找原因: <fields> ***<field name="productName" type="tex ...

  7. 安卓手机数据恢复软件-DiskDigger Pro

    以前的手机是支持大容量存储模式,可以被分配到盘符,但是自从手机不支持U盘大容量存储模式只能MTP模式之后,想要做数据恢复麻烦了很多啊! 经过多方查找,终于找到了这个能在手机上用的软件DiskDigge ...

  8. Jbpm4.4 使用

    最近工作项目中需要用到工作流.于是找到了jbpm.关于jbpm的一些概念就不说了 1) 首先下载jbpm,这里我选择了jbpm4.4 从官网上可以下载  http://sourceforge.net/ ...

  9. RTX——第18章 内存管理

    以下内容转载自安富莱电子: http://forum.armfly.com/forum.php 内存管理介绍在 ANSI C 中,可以用 malloc()和 free()2 个函数动态的分配内存和释放 ...

  10. Codeforces Round #257 (Div. 2) E题:Jzzhu and Apples 模拟

    E. Jzzhu and Apples time limit per test 1 second memory limit per test 256 megabytes input standard ...