• 企业400电话
  • 微网小程序
  • AI电话机器人
  • 电商代运营
  • 全 部 栏 目

    企业400电话 网络优化推广 AI电话机器人 呼叫中心 网站建设 商标✡知产 微网小程序 电商运营 彩铃•短信 增值拓展业务
    Asp.net程序优化js、css实现合并与压缩的方法

    本文实例讲述了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();

                        // 开始压缩文件
                        if (IsCompress)
                        {
                            if (type.Equals("js"))
                            {
                                content = JavaScriptCompressor.Compress(content);
                            }
                            else if (type.Equals("css"))
                            {
                                content = CssCompressor.Compress(content);
                            }
                        }

                        //输入到客户端还可以进行Gzip压缩 ,这里就省略了

                        cacheItem = new CompressCacheItem() { Type = type, Content = content, Expires = DateTime.Now.AddDays(30) };
                        HttpRuntime.Cache.Insert(cachekey, cacheItem, null, cacheItem.Expires, TimeSpan.Zero);
                    }

                    string ifModifiedSince = request.Headers["If-Modified-Since"];
                    if (!string.IsNullOrEmpty(ifModifiedSince)
                        TimeSpan.FromTicks(cacheItem.Expires.Ticks - DateTime.Parse(ifModifiedSince).Ticks).Seconds 0)
                    {
                        response.StatusCode = (int)System.Net.HttpStatusCode.NotModified;
                        response.StatusDescription = "Not Modified";
                    }
                    else
                    {
                        response.Write(cacheItem.Content);
                        SetClientCaching(response, cacheItem.Expires);
                    }
                }
            }

            private void SetClientCaching(HttpResponse response, DateTime expires)
            {
                response.Cache.SetETag(DateTime.Now.Ticks.ToString());
                response.Cache.SetLastModified(DateTime.Now);

                //public 以指定响应能由客户端和共享(代理)缓存进行缓存。   
                response.Cache.SetCacheability(HttpCacheability.Public);

                //是允许文档在被视为陈旧之前存在的最长绝对时间。
                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; }
            }
    }

    最后在配置文件中配置一下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" />

    希望本文所述对大家的asp.net程序设计有所帮助。

    您可能感兴趣的文章:
    • 使用asp.net MVC4中的Bundle遇到的问题及解决办法分享
    • 基于Asp.Net MVC4 Bundle捆绑压缩技术的介绍
    • asp.net Bundle功能扩展
    • ASP.NET MVC Bundles 用法和说明(打包javascript和css)
    • ASP.NET MVC中使用Bundle打包压缩js和css的方法
    • 浅谈ASP.NET中MVC 4 的JS/CSS打包压缩功能
    • Asp.net MVC下使用Bundle合并、压缩js与css文件详解
    上一篇:asp.net实现文件无刷新上传方法汇总
    下一篇:完美兼容ie和firefox的asp.net网站加入收藏和设置主页
  • 相关文章
  • 

    © 2016-2020 巨人网络通讯

    时间:9:00-21:00 (节假日不休)

    地址:江苏信息产业基地11号楼四层

    《增值电信业务经营许可证》 苏B2-20120278

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