Asp.net程序优化js、css实现合并与压缩的方法

访问时将js和css压缩并且缓存在客户端,
采用的是Yahoo.Yui.Compressor组件来完成的,用户可以点击此处本站下载

创建一个IHttpHandler来处理文件

复制代码 代码如下:


public class CombineFiles : IHttpHandler
{
        private const string CacheKeyFormat = "_CacheKey_{0}_";

private const bool IsCompress = true; //需要压缩

public bool IsReusable
        {
            get
            {
                return false;
            }
        }

public void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;
            HttpResponse response = context.Response;

string cachekey = string.Empty;

string type = request.QueryString["type"];
            if (!string.IsNullOrEmpty(type) && (type == "css" || type == "js"))
            {
                if (type == "js")
                {
                    response.ContentType = "text/javascript";

}
                else if (type == "css")
                {
                    response.ContentType = "text/css";
                }

cachekey = string.Format(CacheKeyFormat, type);

CompressCacheItem cacheItem = HttpRuntime.Cache[cachekey] as CompressCacheItem;
                if (cacheItem == null)
                {
                    string content = string.Empty;
                    string path = context.Server.MapPath("");
                    //找到这个目录下所有的js或css文件,当然也可以进行配置,需求请求压缩哪些文件
                    //这里就将所的有文件都请求压缩
                    string[] files = Directory.GetFiles(path, "*." + type);
                    StringBuilder sb = new StringBuilder();
                    foreach (string fileName in files)
                    {
                        if (File.Exists(fileName))
                        {
                            string readstr = File.ReadAllText(fileName, Encoding.UTF8);
                            sb.Append(readstr);
                        }
                    }

content = sb.ToString();

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjzzfg.html