Asp.net MVC js,css单位合并 单位压缩
欢迎进入.NET社区论坛,与300万技术人员互动交流 >>进入
上次写了两篇有关js的校园如web优化之-mvc js单位合并 单位压缩 去掉js重复引用 js缓存 js延迟加载web优化之-asp.net js延迟加载 js单位合并 js单位压缩看了一下的访问两比较大,现在js和css的校园整理一下。
首先还是需要一个handler来处理文件的合并、压缩、缓存,.js和css的压缩我们采用的是Yahoo.Yui.Compressor,所以需要引用Yahoo.Yui.Compressor.dll文件
代码如下:
[csharp] view plaincopyprint?public class CombineFiles : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/javascript";
HttpRequest request = context.Request;
HttpResponse response = context.Response;
string[] allkeys = request.QueryString.AllKeys;
if (!allkeys.Contains("href") || !allkeys.Contains("type") || !allkeys.Contains("compress"))
{
response.Write("请求格式不正确,正确格式是type=…&href=…&compress=…");
response.Write("type只能是js或则css,compress只能是true或则false,href则是请求的文件,多个文件已逗号分隔");
}
else
{
string cacheKey = request.Url.Query;
#region /*确定合并文件类型*/
string fileType = request.QueryString["type"].Trim()。ToLower();
string contenType = string.Empty;
if (fileType.Equals("js"))
{
contenType = "text/javascript";
}
else if (fileType.Equals("css"))
{
contenType = "text/css";
}
/*确定合并文件类型*/
#endregion
CacheItem cacheItem = HttpRuntime.Cache.Get(cacheKey) as CacheItem;//服务端缓存
if (cacheItem == null)
{
#region 校园文件
/*合并文件*/
string href = context.Request.QueryString["href"].Trim();
string content = string.Empty;
string[] files = href.Split(new string[] { ",", "," }, StringSplitOptions.RemoveEmptyEntries);
StringBuilder sb = new StringBuilder();
foreach (string fileName in files)
{
string filePath = context.Server.MapPath(fileName);
if (File.Exists(filePath))
{
string readstr = File.ReadAllText(filePath, Encoding.UTF8);
sb.Append(readstr);
//content = JavaScriptCompressor.Compress(content);
//response.Write(content);
}
else
{
sb.AppendLine("\r\n未找到源文件" + filePath + "\r\n");
}
}
content = sb.ToString();
/*合并文件*/
/*压缩文件*/
[1]
【责编:peter】