Asp.net程式最佳化js、css實現合并與壓縮的方法_實用技巧

來源:互聯網
上載者:User

本文執行個體講述了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程式設計有所協助。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.