為了更好的進行封裝,每個實現不同功能的js代碼應該有自己的js文件,這樣如果一個網頁中引用了多個js文件,如下
復制代碼 代碼如下:
<script type="text/javascript" src="limit.js"></script>
<script type="text/javascript" src="select.js"></script>
<script type="text/javascript" src="rating.js"></script>
這樣網頁會向服務器發送3個請求,請求3個js文件,其實完全沒有必要發這麼多的請求,一個足矣,下面就來介紹如何用Handler實現
新建一個HttpHandler
復制代碼 代碼如下:
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{//原文鏈接:blog.csdn.net/bluceyoung
string[] js = context.Request.Url.LocalPath.Substring(1, context.Request.Url.LocalPath.Length - 5).Split('.');
StringBuilder sb = new StringBuilder();
foreach (string j in js)
{
sb.Append(ReadFile(j+".js"));
}
context.Response.Write(CompressStr(sb));
}
private string ReadFile(string fileName)
{
string directory = @"D:\SRC\bluceyoung\";
if (!File.Exists(directory + fileName))
{
return "";
}
string result;
using (FileStream fs = new FileStream(directory + fileName, FileMode.Open))
{
using (StreamReader sr = new StreamReader(fs))
{
result = sr.ReadToEnd();
}
}
return result;
}
private string CompressStr(StringBuilder sb)
{
while (true)
{
int length = sb.Length;
sb.Replace(" ", " ");
if (length == sb.Length)
break;
}
sb.Replace("\r\n", "").Replace("\t", "").Replace("; ", ";").Replace(" }", "}").Replace("} ", "}").Replace(" ;", ";").Replace(" {", "{").Replace("{ ", "{");
return sb.ToString();
}
public bool IsReusable
{
get
{
return false;
}
}
}
配置文件中添加節點
復制代碼 代碼如下:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpHandlers>
<add path="*.jsx" verb="*" type="BluceYoung.Handler1"/>
</httpHandlers><!--原文博客:blog.csdn.net/bluceyoung -->
</system.web>
</configuration>
頁面調用
復制代碼 代碼如下:
<script src="limit.select.rating.jsx" type="text/javascript"></script>
就這樣,一個script引用就完成了多個js文件的請求,並且對文件進行了壓縮處理