温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Asp.net程序优化js、css如何实现合并与压缩

发布时间:2021-08-23 09:33:34 来源:亿速云 阅读:138 作者:小新 栏目:开发技术

这篇文章主要为大家展示了“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程序优化js、css如何实现合并与压缩”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI