Asp.net程序優(yōu)化js、css實(shí)現(xiàn)合并與壓縮的方法
本文實(shí)例講述了Asp.net程序優(yōu)化js、css實(shí)現(xiàn)合并與壓縮的方法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:
訪問時將js和css壓縮并且緩存在客戶端,
采用的是Yahoo.Yui.Compressor組件來完成的,用戶可以點(diǎn)擊此處本站下載。
創(chuàng)建一個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文件,當(dāng)然也可以進(jìn)行配置,需求請求壓縮哪些文件
//這里就將所的有文件都請求壓縮
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);
}
}
//輸入到客戶端還可以進(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);
//是允許文檔在被視為陳舊之前存在的最長絕對時間。
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>
/// 過期時間
/// </summary>
public DateTime Expires { set; get; }
}
}
最后在配置文件中配置一下CombineFiles.axd文件,具體配置略
引用如下
<link rel="stylesheet" type="text/css" href="/css/CombineFiles.axd?type=css" />
希望本文所述對大家的asp.net程序設(shè)計(jì)有所幫助。
相關(guān)文章
asp.net DataTable相關(guān)操作集錦(篩選,取前N條數(shù)據(jù),去重復(fù)行,獲取指定列數(shù)據(jù)等)
這篇文章主要介紹了asp.net DataTable相關(guān)操作,包括篩選,取前N條數(shù)據(jù),去重復(fù)行,獲取指定列數(shù)據(jù)等.基本涵蓋了DataTable的常見操作技巧,需要的朋友可以參考下2016-06-06
擴(kuò)展方法ToJSON() and ParseJSON()
AJAX編程經(jīng)常需要Object<=>JSON之間轉(zhuǎn)換,寫了二個擴(kuò)展方法: public static string ToJSON(this object obj) public static T ParseJSON<T>(this string str)2008-03-03
asp.net 仿微信端菜單設(shè)置實(shí)例代碼詳解
本文通過實(shí)例代碼給大家介紹了asp.net 仿微信端菜單設(shè)置方法,代碼簡單易懂,非常不錯,具有一定的參考借鑒價值 ,需要的朋友可以參考下2018-11-11
vs2010根據(jù)字符串內(nèi)容添加斷點(diǎn)的方法介紹
這篇文章介紹了vs2010根據(jù)字符串內(nèi)容添加斷點(diǎn)的方法,有需要的朋友可以參考一下2013-08-08
利用Timer在ASP.NET中實(shí)現(xiàn)計(jì)劃任務(wù)的方法
利用Timer在ASP.NET中實(shí)現(xiàn)計(jì)劃任務(wù)的方法...2007-04-04
Visual Studio 2017 IDE安裝使用圖文教程
這篇文章主要為大家詳細(xì)介紹了Visual Studio 2017 IDE安裝使用圖文教程,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-09-09

