溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

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

發(fā)布時(shí)間:2021-08-23 09:33:34 來源:億速云 閱讀:147 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要為大家展示了“Asp.net程序優(yōu)化js、css如何實(shí)現(xiàn)合并與壓縮”,內(nèi)容簡(jiǎn)而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“Asp.net程序優(yōu)化js、css如何實(shí)現(xiàn)合并與壓縮”這篇文章吧。

具體實(shí)現(xiàn)方法如下:

訪問時(shí)將js和css壓縮并且緩存在客戶端,
采用的是Yahoo.Yui.Compressor組件來完成的,用戶可以點(diǎn)擊此處本站下載。

創(chuàng)建一個(gè)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("");
                    //找到這個(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();
                    // 開始?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>
            /// 過期時(shí)間
            /// </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程序優(yōu)化js、css如何實(shí)現(xiàn)合并與壓縮”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI