本文實例講述了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;
新聞熱點
疑難解答
圖片精選