Skip to content

HTML Minifier

Andrey Taritsyn edited this page Aug 2, 2015 · 31 revisions

HTML Minifier produces minification of HTML and XHTML code. As a result of minification on the output we get valid HTML code.

Consider a simple example of usage of the HTML Minifier:

using System;
using System.Collections.Generic;

using WebMarkupMin.Core;

namespace WebMarkupMin.Sample.ConsoleApplication
{
	class Program
	{
		static void Main(string[] args)
		{
			const string htmlInput = @"<!DOCTYPE html>
<html>
	<head>
		<meta charset=""utf-8"" />
		<title>The test document</title>
		<link href=""favicon.ico"" rel=""shortcut icon"" type=""image/x-icon"" />
		<meta name=""viewport"" content=""width=device-width"" />
		<link rel=""stylesheet"" type=""text/css"" href=""/Content/Site.css"" />
	</head>
	<body>
		<p>Lorem ipsum dolor sit amet...</p>

		<script src=""http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js""></script>
		<script>
			(window.jquery) || document.write('<script src=""/Scripts/jquery-1.9.1.min.js""><\/script>');
		</script>
	</body>
</html>";

			var htmlMinifier = new HtmlMinifier();

			MarkupMinificationResult result = htmlMinifier.Minify(htmlInput,
				generateStatistics: true);
			if (result.Errors.Count == 0)
			{
				MinificationStatistics statistics = result.Statistics;
				if (statistics != null)
				{
					Console.WriteLine("Original size: {0:N0} Bytes",
						statistics.OriginalSize);
					Console.WriteLine("Minified size: {0:N0} Bytes",
						statistics.MinifiedSize);
					Console.WriteLine("Saved: {0:N2}%",
						statistics.SavedInPercent);
				}
				Console.WriteLine("Minified content:{0}{0}{1}",
					Environment.NewLine, result.MinifiedContent);
			}
			else
			{
				IList<MinificationErrorInfo> errors = result.Errors;

				Console.WriteLine("Found {0:N0} error(s):", errors.Count);
				Console.WriteLine();

				foreach (var error in errors)
				{
					Console.WriteLine("Line {0}, Column {1}: {2}",
						error.LineNumber, error.ColumnNumber, error.Message);
					Console.WriteLine();
				}
			}
		}
	}
}

First we create an instance of the HtmlMinifier class, and then call its the Minify method with the following parameters: first parameter contains HTML code, and second - flag for whether to allow generate minification statistics (default value - false, because generation of statistics requires time and additional resources). Minify method returns an object of the MarkupMinificationResult type, which has the following properties:

  • MinifiedContent - minified HTML code;
  • Errors - list of errors, that occurred during minification;
  • Warnings - list of warnings about the problems, which were found during minification;
  • Statistics - statistical information about minified code.

If list of errors is empty, then print minification statistics and minified code to the console, otherwise print error information to the console.

Consider an example of a more advanced usage of the HTML Minifier:

using System;
using System.Collections.Generic;
using System.Text;

using WebMarkupMin.Core;
using WebMarkupMin.Core.Loggers;

namespace WebMarkupMin.Sample.ConsoleApplication
{
	class Program
	{
		static void Main(string[] args)
		{
			const string htmlInput = @"<!DOCTYPE html>
<html>
	<head>
		<meta charset=""utf-8"" />
		<title>The test document</title>
		<link href=""favicon.ico"" rel=""shortcut icon"" type=""image/x-icon"" />
		<meta name=""viewport"" content=""width=device-width"" />
		<link rel=""stylesheet"" type=""text/css"" href=""/Content/Site.css"" />
	</head>
	<body>
		<p>Lorem ipsum dolor sit amet...</p>

		<script src=""http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js""></script>
		<script>
			(window.jquery) || document.write('<script src=""/Scripts/jquery-1.9.1.min.js""><\/script>');
		</script>
	</body>
</html>";

			var settings = new HtmlMinificationSettings();
			var cssMinifier = new KristensenCssMinifier();
			var jsMinifier = new CrockfordJsMinifier();
			var logger = new NullLogger();

			var htmlMinifier = new HtmlMinifier(settings, cssMinifier,
				jsMinifier, logger);

			MarkupMinificationResult result = htmlMinifier.Minify(htmlInput,
				fileContext: string.Empty, encoding: Encoding.Default,
				generateStatistics: false);
			if (result.Errors.Count == 0)
			{
				Console.WriteLine("Minified content:{0}{0}{1}",
					Environment.NewLine, result.MinifiedContent);
			}
			else
			{
				IList<MinificationErrorInfo> errors = result.Errors;

				Console.WriteLine("Found {0:N0} error(s):", errors.Count);
				Console.WriteLine();

				foreach (var error in errors)
				{
					Console.WriteLine("Line {0}, Column {1}: {2}",
						error.LineNumber, error.ColumnNumber, error.Message);
					Console.WriteLine();
				}
			}
		}
	}
}

When creating an instance of the HtmlMinifier class, we pass through the constructor: HTML minification settings, CSS minifier, JS minifier and logger. In the Minify method passed another two additional parameters:

  • fileContext. Can contain a path to the file or URL of the web page. The value of this parameter is used when logging.
  • encoding. Contains a text encoding, which is used in the minification process and statistics generation.

The values of parameters in the above code correspond to the default values.

Clone this wiki locally