CSS/JS GZip Compression with Asp.Net

2020-05-19 05:12发布

问题:

I am currently on a hosted Virtual Server, I want to enable GZip compression for my Asp.Net 3.5 site, how do I go about starting?

I have tried using 'packed' JS files, but they don't work, I am assuming it's because they are not handled correctly...?

回答1:

GZIP should be handled by IIS, what version of IIS are you running?

The client is responsible for asking the server for a GZiped version. The server will be looking for two things, the request is http 1.1, and a header of Accept-Encoding: gzip. An easy way to look for these headers is to use firebug

IIS6 - GZip can be enabled with the iis snap-in. Microsofts MSDN Topic On Gzip With IIS6

IIS7 - GZip can be enabled with the web.config using httpCompression xml tag Nick Berardi's Getting IIS 7 to Compress JavaScript

By minifying and packing javascript files, your decreasing the total size of JavaScript by removing whitespace and shortening your variables names.



回答2:

My preferred way of doing this would be to using a compression tool like YUI Compressor and make it part of the build process (After minifying, the compression ratio won’t be so high. Or you can use both. Point being that you shouldn’t miss the greater performance problem given below).

One of the main problems with compression by IIS is that it doesn’t pack all the JS/CSS files into a single file. So if your site has 7 JS files and 20 CSS (surprisingly this is very common) it will take 27 HTTP round trip to get your data. Writing a HTTP handler to do this is a good idea for people with shared hosting.

A simple build algo would be to have a make file in the JS/CSS root directory

If(build.config == release) {
Add your js file in order to the make files.
    e.g. jQuery.js jQuery.form.js  jQuery.container.js custom.js 
Split and pass it as params to YUI
Compress
O/P to site.js 
Delete all the above files.
}

In release mode you page master should only refer site.js

Edit: Here's a link to get YUI and nant integrated.
Edit: Justin Etheredge has released an awesome tool to combine and compress css/js file called SquishIt.



回答3:

You could also use code to GZip the scripts. The way it works is that you use an ASP.NET page to deliver the compressed file along with the correct headers (telling the browser that this stream is compressed). I've written an article how to utilize GZip compression along with minifying (using YUI) and bundling the scripts (less round trips to the server), you'll find it at http://www.codeproject.com/KB/custom-controls/smartinclude.aspx



回答4:

I've been using a handy little server control for my CSS minification, called StyleManager. It uses YUI Compressor under-the-hood.

It's easier to add to your site than adding YUI C manually, and its usage is a lot like asp.net's ScriptManager, so it's quick to get used to.

Most importantly - it combines your CSS files too. So instead of having like 10 CSS files to download it'll just be 1, which will also be compressed etc.

Check it out - gStyleManager.com



回答5:

I second that IIS is the place to configure this. If you can't directly change IIS you can add a handler to all requests which checks for the Accept-Encoding: gzip or deflate settings. Then you do the right compression using something like SharpZipLib. However this gets kludgey quickly.

You will find some limited success in manually gzipping your static files like css or js. Say you include styles.css.gz and scripts.js.gz in your html, and you map the gz extension to the mimetype for gzipped text (is it application/x-gzip?) a lot of browsers (ie, firefox, safari, maybe chrome) will handle it just fine. But some browsers won't, and you're leaving them out (links, maybe older opera).



回答6:

I would consider using "deflate" for the same as it is more efficient than GZip. I've added codes for both.

For adding this to your site, create a text file and copy paste the undergiven codes to the file and then save it as Global.asax. Now, add this file to the root of your site.

<%@ Application Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.IO.Compression" %>
<script runat="server">
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 == "*")
        {
        // defalte
            app.Response.Filter = new DeflateStream(prevUncompressedStream,
                CompressionMode.Compress);
            app.Response.AppendHeader("Content-Encoding", "deflate");
        }
        else if (acceptEncoding.Contains("gzip"))
        {
            // gzip
            app.Response.Filter = new GZipStream(prevUncompressedStream,
                CompressionMode.Compress);
            app.Response.AppendHeader("Content-Encoding", "gzip");
        }
    }
</script>


回答7:

The previous post works well for aspx pages but not for css and js files. The trick to include css and js files in the compression is to:

  1. change the file extensions of your .css and .js files to .css.aspx and .js.aspx
  2. insert <%@ Page ContentType="text/css" %> and <%@ Page ContentType="text/javascript" %> in the .css.aspx and .js.aspx files
  3. include the .css.aspx and .js.aspx files instead of the .css and .js files in your pages