Windows 2003WebFormsVisual Studio 2008.NET 3.0Visual Studio 2005Windows XP.NET 2.0XML.NET 3.5中级开发Visual StudioWindows.NETASP.NETC#
适用于 ASP.NET 应用程序的 JavaScript 文件压缩器






1.62/5 (4投票s)
使用此 HTTP 处理程序压缩 JavaScript 文件。
引言
本文档解释了如何在浏览器渲染时压缩 js 文件。
使用代码
下载代码并构建 DLL。创建一个网站,并将 DLL 的引用添加到网站。在 Web.Config 文件中,在 HttpHandlers
部分添加一个新的 HTTP 处理程序
<add verb="*" path="*.js" validate="false"
type="ClassLibrary1.Handler, ClassLibrary1, Version=1.0.0.0, Culture=neutral" />
就这样了。剩下的工作将由我们的处理程序完成。现在,让我们看看它是如何工作的。
基本上,HttpHandlers 用于处理 Web 应用程序的请求。此处理程序用于处理 JavaScript 文件。它删除空格、换行符、内联注释和多行注释。Handler
类继承自 IHttpHandler
接口,并实现了 ProcessRequest
方法
//Getting the script file name from request
Uri url = context.Request.Url;
string filename = url.Segments[url.Segments.Length-1];
//Creating a file stream to read the script file.
FileStream fs = new FileStream(context.Server.MapPath(filename), FileMode.Open);
StreamReader sr = new StreamReader(fs);
string js = sr.ReadToEnd();
string a = string.Empty , b = string.Empty;
//Removing the single line comments
while (js.IndexOf("//")!=-1)
{
a = js.Substring(0, js.IndexOf("//"));
b = js.Substring(js.IndexOf("\r\n", js.IndexOf("//")));
js = a+b;
}
//Removing multiline comments
while (js.IndexOf("/*") != -1)
{
a = js.Substring(0, js.IndexOf("/*"));
b = js.Substring(js.IndexOf("*/", js.IndexOf("/*"))+2);
js = a + b;
}
//To Remove Blank spaces
js = js.Replace(" ", string.Empty);
//To remove Carrige retun and new line character
js = js.Replace("\r", string.Empty);
js = js.Replace("\n", string.Empty);
//Flushing it in response
context.Response.Write(js);
//Closing the resourses used
sr.Close();
fs.Close();
sr.Dispose();
fs.Dispose();
这使得文件被压缩,如果任何入侵者试图访问您的代码,他会觉得很难追溯功能,因为缩进和注释丢失了。但他如果很有耐心仍然可以做到:)。