国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > .NET > 正文

Asp.net程序優(yōu)化js、css實(shí)現(xiàn)合并與壓縮的方法

2024-07-10 13:28:39
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友
這篇文章主要介紹了Asp.net程序優(yōu)化js、css實(shí)現(xiàn)合并與壓縮的方法,使用第三方組件實(shí)現(xiàn)訪問(wèn)時(shí)將js與css文件壓縮并緩存在客戶端的效果,非常具有實(shí)用價(jià)值,需要的朋友可以參考下
 
 

本文實(shí)例講述了Asp.net程序優(yōu)化js、css實(shí)現(xiàn)合并與壓縮的方法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:

訪問(wèn)時(shí)將js和css壓縮并且緩存在客戶端,
采用的是Yahoo.Yui.Compressor組件來(lái)完成的。

創(chuàng)建一個(gè)IHttpHandler來(lái)處理文件

 

復(fù)制代碼代碼如下:

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("");
                    //找到這個(gè)目錄下所有的js或css文件,當(dāng)然也可以進(jìn)行配置,需求請(qǐng)求壓縮哪些文件
                    //這里就將所的有文件都請(qǐng)求壓縮
                    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();

                    // 開(kāi)始?jí)嚎s文件
                    if (IsCompress)
                    {
                        if (type.Equals("js"))
                        {
                            content = JavaScriptCompressor.Compress(content);
                        }
                        else if (type.Equals("css"))
                        {
                            content = CssCompressor.Compress(content);
                        }
                    }

                    //輸入到客戶端還可以進(jìn)行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 以指定響應(yīng)能由客戶端和共享(代理)緩存進(jìn)行緩存。    
            response.Cache.SetCacheability(HttpCacheability.Public);

            //是允許文檔在被視為陳舊之前存在的最長(zhǎng)絕對(duì)時(shí)間。 
            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>
            /// 內(nèi)容
            /// </summary>
            public string Content { set; get; }
            /// <summary>
            /// 過(guò)期時(shí)間
            /// </summary>
            public DateTime Expires { set; get; }
        }
}

 

最后在配置文件中配置一下CombineFiles.axd文件,具體配置略

引用如下

復(fù)制代碼代碼如下:
<script type="text/javascript" src="/js/CombineFiles.axd?type=js"></script>
<link rel="stylesheet" type="text/css" href="/css/CombineFiles.axd?type=css" />

 

希望本文所述對(duì)大家的asp.net程序設(shè)計(jì)有所幫助。


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 安图县| 清水河县| 龙州县| 温州市| 德安县| 岳阳县| 安平县| 湘乡市| 仁布县| 昌乐县| 新昌县| 扬州市| 长子县| 西昌市| 绥江县| 盐亭县| 和田县| 沅江市| 卓尼县| 龙山县| 长春市| 楚雄市| 辽源市| 黄浦区| 龙山县| 汝州市| 仙游县| 沂水县| 温州市| 乌兰浩特市| 武安市| 会同县| 诸城市| 鄂州市| 饶阳县| 成安县| 沙湾县| 敦煌市| 昌平区| 台中市| 南木林县|