Compress JavaScript and CSS in Asp.Net WebForm
I use C# Asp.net 4, I have this script in Global.a开发者_JAVA技巧sax. I'm able to gzip all asp.net pages but NOT JavaScripts and CSS. I would like to know if is possible have compressed CSS and JS directly in my web app or it possible just in IIS. If is possible please point me out what I miss in my code. Thanks
protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
string acceptEncoding = app.Request.Headers["Accept-Encoding"];
Stream prevUncompressedStream = app.Response.Filter;
if (!(app.Context.CurrentHandler is Page ||
app.Context.CurrentHandler.GetType().Name == "SyncSessionlessHandler") ||
app.Request["HTTP_X_MICROSOFTAJAX"] != null)
return;
if (acceptEncoding == null || acceptEncoding.Length == 0)
return;
acceptEncoding = acceptEncoding.ToLower();
// if (acceptEncoding.Contains("deflate") || acceptEncoding == "*")
if (acceptEncoding.Contains("gzip") || acceptEncoding == "*")
{
// gzip
app.Response.Filter = new GZipStream(prevUncompressedStream,
CompressionMode.Compress);
app.Response.AppendHeader("Content-Encoding", "gzip");
}
// else if (acceptEncoding.Contains("gzip"))
else if (acceptEncoding.Contains("deflate"))
{
// defalte
app.Response.Filter = new DeflateStream(prevUncompressedStream,
CompressionMode.Compress);
app.Response.AppendHeader("Content-Encoding", "deflate");
}
}
Are you sure that *.css and *.js are handled by the ASP.NET runtime? They are not by default, you'd for example have to set the runAllManagedModulesForAllRequests
to true
in web.config
.
Also, why don't you rely on the IIS built-in compression?
Minify and gzip your CSS and JS ahead of time, also combine all the JS in one file and all CSS in one file:
Online JavaScript/CSS Compression Using YUI Compressor
If you search a little you will find all kinds of way to automate the compression and minification into a post-build process or CI build process.
You can and should set up IIS to compress static files. Let IIS handle it before it even gets to your app.
You can set this manually in IIS Management Console or use the <httpCompression>
setting in your web.config.
Yes, we can take the advantage of IIS 7.0 compression fearutres. Also you are really concerned about performance, it is always better to create one JS and one CSS in your applications, if this is not possible, it is better to merge those JS and CCS into one Js and CSS. And also it is always recommended to us AJAX Minifier.
http://www.mindfiresolutions.com/How-to-merge-your-Javascript-files-in-ASPNET-1221.php
http://www.mindfiresolutions.com/How-to-merge-CSS-files-in-ASPNET-1230.php
Please feel free to contact me if you need further help in this.
Thanks, Himanshu Shekhar Sahu www.mindfiresolutions.com
精彩评论