Introduction
This article explains how to compress a js file while rendering by the browser.
Using the code
Download the code and build the DLL. Create a Website, and add a reference of the DLL to the Website. In the Web.Config file, add a new HTTP Handler in the HttpHandlers
section:
<add verb="*" path="*.js" validate="false"
type="ClassLibrary1.Handler, ClassLibrary1, Version=1.0.0.0, Culture=neutral" />
That's all. The rest of the work will be done by our handler. Now, let us see how it works.
Basically, the HttpHandlers are used to handle requests of a Web Application. This handler is used to handle the JavaScript file. It removes white spaces, new line characters, inline comments, and multiline comments. The Handler
class is inherited from the IHttpHandler
Interface, and it implements the ProcessRequest
method:
Uri url = context.Request.Url;
string filename = url.Segments[url.Segments.Length-1];
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;
while (js.IndexOf("//")!=-1)
{
a = js.Substring(0, js.IndexOf("//"));
b = js.Substring(js.IndexOf("\r\n", js.IndexOf("//")));
js = a+b;
}
while (js.IndexOf("/*") != -1)
{
a = js.Substring(0, js.IndexOf("/*"));
b = js.Substring(js.IndexOf("*/", js.IndexOf("/*"))+2);
js = a + b;
}
js = js.Replace(" ", string.Empty);
js = js.Replace("\r", string.Empty);
js = js.Replace("\n", string.Empty);
context.Response.Write(js);
sr.Close();
fs.Close();
sr.Dispose();
fs.Dispose();
This makes the file compressed, and if any intruder tries to access your code, he will feel difficult to trace back the functionalities since the indentation and comments are missing. But he can still do it if he has patience:).