user3140096
user3140096

Reputation:

Best way to minify html in an asp.net mvc 5 application

I came across several articles about this topic but most of them are outdated. So what is the best way to minify/get rid of the whitespaces when outputing my views html?

Upvotes: 4

Views: 6626

Answers (2)

Tom Pažourek
Tom Pažourek

Reputation: 10207

I built a very trivial minifier called RazorHtmlMinifier.Mvc5.

It's operating in compile-time when the cshtml Razor files are converted to C# classes, so it won't have any performance overhead at runtime.

The minification is very trivial, basically just replacing multiple spaces with one (because sometimes a space is still significant, e.g. <span>Hello</span> <span>World</span> is different to <span>Hello</span><span>World</span>).

The source code is very recent and very simple (just one file with less than 100 lines of code) and installation involves just a NuGet package and changing one line in Web.config file.

And all of this is built for the latest version of ASP.NET MVC 5.


Usually, it's recommended to use gzip encoding to minify HTTP responses, but I found out that if you minify the HTML before gzipping, you can still get around 11% smaller responses on average. In my opinion, it's still worth it.

Upvotes: 4

nmit026
nmit026

Reputation: 3392

Use WebMarkupMin: ASP.NET 4.X MVC. Install the NuGet package and then use the MinifyHtmlAttribute on your action method, controller, or register it in RegisterGlobalFilters in FilterConfig. You can also try the CompressContentAttribute. Here's the wiki: https://github.com/Taritsyn/WebMarkupMin/wiki/WebMarkupMin:-ASP.NET-4.X-MVC

If you use the CompressContentAttribute you'll see the Content-Encoding:deflate header rather than Content-Encoding:gzip header if you were using gzip before applying this attribute.

Some test numbers:

No minification or compression: Content-Length:21594

Minification only: Content-Length:19869

Minification and compression: Content-Length:15539

You'll have to test to see if you're getting speed improvements overall from your changes.

EDIT:

After exhaustive testing locally and on the live site, I've concluded that minifying and compressing HTML with WebMarkupMin in my case slowed the page load time by about 10%. Just compressing (using CompressContentAttribute) or just minifying also slowed it down. So I've decided not to compress (using CompressContentAttribute) or minify my HTML at all.

Upvotes: 2

Related Questions