List of the most important classes, that contained in the WebMarkupMin.Core: three markup minifiers (HtmlMinifier, XhtmlMinifier and XmlMinifier), two built-in CSS minifiers (KristensenCssMinifier and NullCssMinifier), two built-in JavaScript minifiers (CrockfordJsMinifier and NullJsMinifier) and two loggers (ThrowExceptionLogger and NullLogger).
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:
namespace WebMarkupMin.Example.Console { using System; using System.Collections.Generic; using WebMarkupMin.Core; using WebMarkupMin.Core.Minifiers; 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:
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:
namespace WebMarkupMin.Example.Console { using System; using System.Collections.Generic; using System.Text; using WebMarkupMin.Core; using WebMarkupMin.Core.Loggers; using WebMarkupMin.Core.Minifiers; using WebMarkupMin.Core.Settings; 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:
The values of parameters in the above code correspond to the default values.
And now let's consider in detail properties of the HtmlMinificationSettings class:
Property name | Data type | Default value | Description |
---|---|---|---|
WhitespaceMinificationMode | Enumeration | Medium |
Whitespace minification mode. Can take the following values:
|
RemoveHtmlComments | Boolean | true |
Flag for whether to remove all HTML comments, except conditional, noindex, KnockoutJS containerless comments and AngularJS comment directives. |
RemoveHtmlCommentsFromScriptsAndStyles | Boolean | true |
Flag for whether to remove HTML comments from script and style tags. |
RemoveCdataSectionsFromScriptsAndStyles | Boolean | true |
Flag for whether to remove CDATA sections from script and style tags. |
UseShortDoctype | Boolean | true |
Flag for whether to replace existing document type declaration by short declaration - <!DOCTYPE html>. |
UseMetaCharsetTag | Boolean | true |
Flag for whether to replace <meta http-equiv="content-type" content="text/html; charset=…"> tag by <meta charset="…"> tag |
EmptyTagRenderMode | Enumeration | NoSlash |
Render mode of HTML empty tag. Can take the following values:
|
RemoveOptionalEndTags | Boolean | true |
Flag for whether to remove optional end tags (html, head, body, p, li, dt, dd, rt, rp, optgroup, option, colgroup, thead, tfoot, tbody, tr, th and td). |
RemoveTagsWithoutContent | Boolean | false |
Flag for whether to remove tags without content, except for textarea, tr, th and td tags, and tags with class, id, name, role, src and data-* attributes. |
CollapseBooleanAttributes | Boolean | true |
Flag for whether to remove values from boolean attributes (for example, checked="checked" is transforms to checked). |
RemoveEmptyAttributes | Boolean | true |
Flag for whether to remove attributes, which have empty value (valid attributes are: class, id, name, style, title, lang, dir, event attributes, action attribute of form tag and value attribute of input tag). |
AttributeQuotesRemovalMode | Enumeration | Html5 |
HTML attribute quotes removal mode. Can take the following values:
|
RemoveRedundantAttributes | Boolean | true |
Flag for whether to remove redundant attributes:
|
RemoveJsTypeAttributes | Boolean | true |
Flag for whether to remove type="text/javascript" attributes from script tags. |
RemoveCssTypeAttributes | Boolean | true |
Flag for whether to remove type="text/css" attributes from style and link tags. |
RemoveHttpProtocolFromAttributes | Boolean | false |
Flag for whether to remove the HTTP protocol portion (http:) from URI-based attributes (tags marked with rel="external" are skipped). |
RemoveHttpsProtocolFromAttributes | Boolean | false |
Flag for whether to remove the HTTPS protocol portion (https:) from URI-based attributes (tags marked with rel="external" are skipped). |
RemoveJsProtocolFromAttributes | Boolean | true |
Flag for whether to remove the javascript: pseudo-protocol portion from event attributes. |
MinifyEmbeddedCssCode | Boolean | true |
Flag for whether to minify CSS code in style tags. |
MinifyInlineCssCode | Boolean | true |
Flag for whether to minify CSS code in style attributes. |
MinifyEmbeddedJsCode | Boolean | true |
Flag for whether to minify JS code in script tags. |
MinifyInlineJsCode | Boolean | true |
Flag for whether to minify JS code in event attributes and hyperlinks with javascript: pseudo-protocol. |
ProcessableScriptTypeList | String | empty string |
Comma-separated list of types of script tags, that are processed by minifier (e.g. "text/html", "text/x-kendo-template", "text/ng-template", etc.) Currently only supported the KnockoutJS, Kendo UI (only the data binding syntax) and AngularJS views. |
MinifyKnockoutBindingExpressions | Boolean | false |
Flag for whether to minify the KnockoutJS binding expressions in data-bind attributes and containerless comments. |
MinifyAngularBindingExpressions | Boolean | false |
Flag for whether to minify the AngularJS binding expressions in Mustache-style tags ({{}}) and directives. |
CustomAngularDirectiveList | String | empty string |
Comma-separated list of names of custom AngularJS directives (e.g. btfCarousel), that contain expressions. If value of the MinifyAngularBindingExpressions property equal to true, then the expressions in custom directives will be minified. |
If different parts of your application requires the same HTML minification settings, then you can specify them only once in the configuration file (App.config or Web.config):
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <sectionGroup name="webMarkupMin"> <section name="core" type="WebMarkupMin.Core.Configuration.CoreConfiguration, WebMarkupMin.Core" /> … </sectionGroup> … </configSections> … <webMarkupMin xmlns="http://tempuri.org/WebMarkupMin.Configuration.xsd"> <core> <html whitespaceMinificationMode="Medium" removeHtmlComments="true" removeHtmlCommentsFromScriptsAndStyles="true" removeCdataSectionsFromScriptsAndStyles="true" useShortDoctype="true" useMetaCharsetTag="true" emptyTagRenderMode="NoSlash" removeOptionalEndTags="true" removeTagsWithoutContent="false" collapseBooleanAttributes="true" removeEmptyAttributes="true" attributeQuotesRemovalMode="Html5" removeRedundantAttributes="true" removeJsTypeAttributes="true" removeCssTypeAttributes="true" removeHttpProtocolFromAttributes="false" removeHttpsProtocolFromAttributes="false" removeJsProtocolFromAttributes="true" minifyEmbeddedCssCode="true" minifyInlineCssCode="true" minifyEmbeddedJsCode="true" minifyInlineJsCode="true" processableScriptTypeList="" minifyKnockoutBindingExpressions="false" minifyAngularBindingExpressions="false" customAngularDirectiveList="" /> … </core> … </webMarkupMin> … </configuration>
To get an instance of the HtmlMinificationSettings class with settings from a configuration file, use the following code:
HtmlMinificationSettings settings = WebMarkupMinContext.Current.Markup.GetHtmlMinificationSettings();
You can also create an instance of the HtmlMinifier class, which will use the settings specified in configuration file (HTML minification settings, default CSS minifier, default JS minifier and default logger):
HtmlMinifier htmlMinifier = WebMarkupMinContext.Current.Markup.CreateHtmlMinifierInstance();
XHTML Minifier produces minification of HTML and XHTML code. As a result of minification on the output we get code, that follows the rules of XHTML.
Work with the XHTML Minifier is very similar to working with the HTML Minifier, only difference is that instead of the HtmlMinifier and HtmlMinificationSettings classes need to use the XhtmlMinifier and XhtmlMinificationSettings.
Let's consider in detail properties of the XhtmlMinificationSettings class:
Property name | Data type | Default value | Description |
---|---|---|---|
WhitespaceMinificationMode | Enumeration | Medium |
Whitespace minification mode. Can take the following values:
|
RemoveHtmlComments | Boolean | true |
Flag for whether to remove all HTML comments, except conditional, noindex, KnockoutJS containerless comments and AngularJS comment directives. |
RemoveHtmlCommentsFromScriptsAndStyles | Boolean | true |
Flag for whether to remove HTML comments from script and style tags. |
UseShortDoctype | Boolean | false |
Flag for whether to replace existing document type declaration by short declaration - <!DOCTYPE html>. |
UseMetaCharsetTag | Boolean | false |
Flag for whether to replace <meta http-equiv="content-type" content="text/html; charset=…" /> tag by <meta charset="…" /> tag |
RenderEmptyTagsWithSpace | Boolean | true |
Flag for whether to allow the inserting space before slash in empty tags (for example, true - <br />; false - <br/>). |
RemoveTagsWithoutContent | Boolean | false |
Flag for whether to remove tags without content, except for textarea, tr, th and td tags, and tags with class, id, name, role, src and data-* attributes. |
RemoveEmptyAttributes | Boolean | true |
Flag for whether to remove attributes, which have empty value (valid attributes are: class, id, name, style, title, lang, dir, event attributes, action attribute of form tag and value attribute of input tag). |
RemoveRedundantAttributes | Boolean | true |
Flag for whether to remove redundant attributes:
|
RemoveHttpProtocolFromAttributes | Boolean | false |
Flag for whether to remove the HTTP protocol portion (http:) from URI-based attributes (tags marked with rel="external" are skipped). |
RemoveHttpsProtocolFromAttributes | Boolean | false |
Flag for whether to remove the HTTPS protocol portion (https:) from URI-based attributes (tags marked with rel="external" are skipped). |
RemoveJsProtocolFromAttributes | Boolean | true |
Flag for whether to remove the javascript: pseudo-protocol portion from event attributes. |
MinifyEmbeddedCssCode | Boolean | true |
Flag for whether to minify CSS code in style tags. |
MinifyInlineCssCode | Boolean | true |
Flag for whether to minify CSS code in style attributes. |
MinifyEmbeddedJsCode | Boolean | true |
Flag for whether to minify JS code in script tags. |
MinifyInlineJsCode | Boolean | true |
Flag for whether to minify JS code in event attributes and hyperlinks with javascript: pseudo-protocol. |
ProcessableScriptTypeList | String | empty string |
Comma-separated list of types of script tags, that are processed by minifier (e.g. "text/html", "text/x-kendo-template", "text/ng-template", etc.) Currently only supported the KnockoutJS, Kendo UI (only the data binding syntax) and AngularJS views. |
MinifyKnockoutBindingExpressions | Boolean | false |
Flag for whether to minify the KnockoutJS binding expressions in data-bind attributes and containerless comments. |
MinifyAngularBindingExpressions | Boolean | false |
Flag for whether to minify the AngularJS binding expressions in Mustache-style tags ({{}}) and directives. |
CustomAngularDirectiveList | String | empty string |
Comma-separated list of names of custom AngularJS directives (e.g. btfCarousel), that contain expressions. If value of the MinifyAngularBindingExpressions property equal to true, then the expressions in custom directives will be minified. |
Just as in case with the HTML minification settings, you can specify the XHTML minification settings in configuration file:
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <sectionGroup name="webMarkupMin"> <section name="core" type="WebMarkupMin.Core.Configuration.CoreConfiguration, WebMarkupMin.Core" /> … </sectionGroup> … </configSections> … <webMarkupMin xmlns="http://tempuri.org/WebMarkupMin.Configuration.xsd"> <core> … <xhtml whitespaceMinificationMode="Medium" removeHtmlComments="true" removeHtmlCommentsFromScriptsAndStyles="true" useShortDoctype="false" useMetaCharsetTag="false" renderEmptyTagsWithSpace="true" removeTagsWithoutContent="false" removeEmptyAttributes="true" removeRedundantAttributes="true" removeHttpProtocolFromAttributes="false" removeHttpsProtocolFromAttributes="false" removeJsProtocolFromAttributes="true" minifyEmbeddedCssCode="true" minifyInlineCssCode="true" minifyEmbeddedJsCode="true" minifyInlineJsCode="true" processableScriptTypeList="" minifyKnockoutBindingExpressions="false" minifyAngularBindingExpressions="false" customAngularDirectiveList="" /> … </core> … </webMarkupMin> … </configuration>
To get an instance of the XhtmlMinificationSettings class with settings from a configuration file, use the following code:
XhtmlMinificationSettings settings = WebMarkupMinContext.Current.Markup.GetXhtmlMinificationSettings();
To create an instance of the XhtmlMinifier class, which will use settings specified in configuration file, use the following code:
XhtmlMinifier xhtmlMinifier = WebMarkupMinContext.Current.Markup.CreateXhtmlMinifierInstance();
XML Minifier produces minification of XML code.
Consider a simple example of usage of the XML Minifier:
namespace WebMarkupMin.Example.Console { using System; using System.Collections.Generic; using WebMarkupMin.Core; using WebMarkupMin.Core.Minifiers; class Program { static void Main(string[] args) { const string xmlInput = @"<?xml version=""1.0"" encoding=""utf-8"" standalone=""yes""?> <urlset xmlns=""http://www.sitemaps.org/schemas/sitemap/0.9""> <url> <loc>http://webmarkupmin.apphb.com/</loc> <changefreq>hourly</changefreq> <priority>0.9</priority> </url> <url> <loc>http://webmarkupmin.apphb.com/minifiers</loc> <changefreq>daily</changefreq> <priority>0.7</priority> </url> <url> <loc>http://webmarkupmin.apphb.com/change-log</loc> <changefreq>daily</changefreq> <priority>0.8</priority> </url> <url> <loc>http://webmarkupmin.apphb.com/contact</loc> <changefreq>weekly</changefreq> <priority>0.4</priority> </url> </urlset>"; var xmlMinifier = new XmlMinifier(); MarkupMinificationResult result = xmlMinifier.Minify(xmlInput, 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(); } } } } }
The above code does not need any comment, because it is very similar to analogous example for the HTML Minifier.
Consider an example of a more advanced usage of the XML Minifier:
namespace WebMarkupMin.Example.Console { using System; using System.Collections.Generic; using System.Text; using WebMarkupMin.Core; using WebMarkupMin.Core.Loggers; using WebMarkupMin.Core.Minifiers; using WebMarkupMin.Core.Settings; class Program { static void Main(string[] args) { const string xmlInput = @"<?xml version=""1.0"" encoding=""utf-8"" standalone=""yes""?> <urlset xmlns=""http://www.sitemaps.org/schemas/sitemap/0.9""> <url> <loc>http://webmarkupmin.apphb.com/</loc> <changefreq>hourly</changefreq> <priority>0.9</priority> </url> <url> <loc>http://webmarkupmin.apphb.com/minifiers</loc> <changefreq>daily</changefreq> <priority>0.7</priority> </url> <url> <loc>http://webmarkupmin.apphb.com/change-log</loc> <changefreq>daily</changefreq> <priority>0.8</priority> </url> <url> <loc>http://webmarkupmin.apphb.com/contact</loc> <changefreq>weekly</changefreq> <priority>0.4</priority> </url> </urlset>"; var settings = new XmlMinificationSettings(); var logger = new NullLogger(); var xmlMinifier = new XmlMinifier(settings, logger); MarkupMinificationResult result = xmlMinifier.Minify(xmlInput, 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(); } } } } }
This example is also very similar to analogous example for the HTML Minifier. Its main difference is that when you create an instance of the XmlMinifier class, there is no need to pass CSS and JS minifiers to its constructor.
Let's consider in detail properties of the XmlMinificationSettings class:
Property name | Data type | Default value | Description |
---|---|---|---|
MinifyWhitespace | Boolean | true |
Flag for whether to minify whitespace. |
RemoveXmlComments | Boolean | true |
Flag for whether to remove all XML comments. |
RenderEmptyTagsWithSpace | Boolean | false |
Flag for whether to allow the inserting space before slash in empty tag. |
CollapseTagsWithoutContent | Boolean | false |
Flag for whether to collapse tags without content (for example, <node></node> is transforms to <node/>). |
Just as in case with the HTML and XHTML minification settings, you can specify the XML minification settings in the configuration file:
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <sectionGroup name="webMarkupMin"> <section name="core" type="WebMarkupMin.Core.Configuration.CoreConfiguration, WebMarkupMin.Core" /> … </sectionGroup> … </configSections> … <webMarkupMin xmlns="http://tempuri.org/WebMarkupMin.Configuration.xsd"> <core> … <xml minifyWhitespace="true" removeXmlComments="true" renderEmptyTagsWithSpace="false" collapseTagsWithoutContent="false" /> … </core> … </webMarkupMin> … </configuration>
To get an instance of the XmlMinificationSettings class with settings from a configuration file, use the following code:
XmlMinificationSettings settings = WebMarkupMinContext.Current.Markup.GetXmlMinificationSettings();
To create an instance of the XmlMinifier class, which will use settings specified in configuration file, use the following code:
XmlMinifier xmlMinifier = WebMarkupMinContext.Current.Markup.CreateXmlMinifierInstance();
CSS minifiers are used in HTML and XHTML minifiers for minification of embedded and inline CSS code. Be a CSS minifier can any class, that implements the ICssMinifier interface.
Instance of the CSS minifier can be created not only in the usual way (by using the new keyword):
var cssMinifier = new KristensenCssMinifier();
But based on settings of configuration file:
<configuration> <configSections> <sectionGroup name="webMarkupMin"> <section name="core" type="WebMarkupMin.Core.Configuration.CoreConfiguration, WebMarkupMin.Core" /> … </sectionGroup> … </configSections> … <webMarkupMin xmlns="http://tempuri.org/WebMarkupMin.Configuration.xsd"> <core> … <css defaultMinifier="KristensenCssMinifier"> <minifiers> <add name="NullCssMinifier" displayName="Null CSS Minifier" type="WebMarkupMin.Core.Minifiers.NullCssMinifier, WebMarkupMin.Core" /> <add name="KristensenCssMinifier" displayName="Mads Kristensen's CSS minifier" type="WebMarkupMin.Core.Minifiers.KristensenCssMinifier, WebMarkupMin.Core" /> … </minifiers> </css> … </core> … </webMarkupMin> … </configuration>
To create an instance of the CSS minifier with settings based on configuration file, it is necessary, first of all, to know under what name it is registered:
ICssMinifier cssMinifier = WebMarkupMinContext.Current.Code.CreateCssMinifierInstance("KristensenCssMinifier");
You can also create an instance of the CSS minifier, which is registered as the default CSS minifier:
ICssMinifier cssMinifier = WebMarkupMinContext.Current.Code.CreateDefaultCssMinifierInstance();
This mechanism simplifies plugging of the external CSS minifiers.
KristensenCssMinifier class implements a simple CSS minifier based on the Mads Kristensen's Efficient stylesheet minifier.
If in your HTML/XHTML code is missing embedded or inline CSS code, you can use instead of the real CSS minifier the stub in the form of NullCssMinifier class. This will allow you to save memory.
JS minifiers are used in HTML and XHTML minifiers for minification of embedded and inline JS code. Be a JS minifier can any class, that implements the IJsMinifier interface.
Instance of the JS minifier can be created not only in the usual way (by using the new keyword):
var jsMinifier = new CrockfordJsMinifier();
But based on settings of configuration file:
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <sectionGroup name="webMarkupMin"> <section name="core" type="WebMarkupMin.Core.Configuration.CoreConfiguration, WebMarkupMin.Core" /> … </sectionGroup> … </configSections> … <webMarkupMin xmlns="http://tempuri.org/WebMarkupMin.Configuration.xsd"> <core> … <js defaultMinifier="CrockfordJsMinifier"> <minifiers> <add name="NullJsMinifier" displayName="Null JS Minifier" type="WebMarkupMin.Core.Minifiers.NullJsMinifier, WebMarkupMin.Core" /> <add name="CrockfordJsMinifier" displayName="Douglas Crockford's JS Minifier" type="WebMarkupMin.Core.Minifiers.CrockfordJsMinifier, WebMarkupMin.Core" /> … </minifiers> </js> … </core> … </webMarkupMin> … </configuration>
To create an instance of the JS minifier with settings based on configuration file, it is necessary, first of all, to know under what name it is registered:
IJsMinifier jsMinifier = WebMarkupMinContext.Current.Code.CreateJsMinifierInstance("CrockfordJsMinifier");
You can also create an instance of the JS minifier, which is registered as the default JS minifier:
IJsMinifier jsMinifier = WebMarkupMinContext.Current.Code.CreateDefaultJsMinifierInstance();
This mechanism simplifies plugging of the external JS minifiers.
CrockfordJsMinifier class implements a simple JS minifier based on the Douglas Crockford's JSMin.
If in your HTML/XHTML code is missing embedded or inline JS code, you can use instead of the real JS minifier the stub in the form of NullJsMinifier class. This will allow you to save memory.
Loggers can to record errors and warnings, that occur during the minification. Be a logger can any class, that implements the ILogger interface or inherits the LoggerBase class.
Loggers, as well as minifiers of CSS and JS code, can be registered in the configuration file:
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <sectionGroup name="webMarkupMin"> <section name="core" type="WebMarkupMin.Core.Configuration.CoreConfiguration, WebMarkupMin.Core" /> … </sectionGroup> … </configSections> … <webMarkupMin xmlns="http://tempuri.org/WebMarkupMin.Configuration.xsd"> <core> … <logging defaultLogger="ThrowExceptionLogger"> <loggers> <add name="NullLogger" displayName="Null Logger" type="WebMarkupMin.Core.Loggers.NullLogger, WebMarkupMin.Core" /> <add name="ThrowExceptionLogger" displayName="Throw exception logger" type="WebMarkupMin.Core.Loggers.ThrowExceptionLogger, WebMarkupMin.Core" /> … </loggers> </logging> … </core> … </webMarkupMin> … </configuration>
To create an instance of the logger based on configuration file, it is necessary, first of all, to know under what name it is registered:
ILogger logger = WebMarkupMinContext.Current.CreateLoggerInstance("ThrowExceptionLogger");
You can also create an instance of the logger, which is registered as the default logger:
ILogger logger = WebMarkupMinContext.Current.CreateDefaultLoggerInstance();
This mechanism makes it possible to quickly and easily plugging your own loggers.
If during of minification an error occured, then the ThrowExceptionLogger class throws exception of the MarkupMinificationException type.
If you prefer to self-handle minification errors, you can use instead of the real logger the stub in the form of NullLogger class.
WebMarkupMin.Web contains classes of HTTP modules, which give the possibility to minify and compress the code generated by ASP.NET:
Listed above HTTP modules a handles only GET requests and responses with status code equals to 200. It should also be noted that HtmlMinificationModule and XhtmlMinificationModule cannot be used together.
HTTP modules, that you want to use, you need to register in the Web.config file:
<?xml version="1.0" encoding="utf-8"?> <configuration> … <system.webServer> <modules> <add name="HtmlMinificationModule" type="WebMarkupMin.Web.HttpModules.HtmlMinificationModule, WebMarkupMin.Web" /> <add name="XmlMinificationModule" type="WebMarkupMin.Web.HttpModules.XmlMinificationModule, WebMarkupMin.Web" /> <add name="CompressionModule" type="WebMarkupMin.Web.HttpModules.CompressionModule, WebMarkupMin.Web" /> </modules> … </system.webServer> … </configuration>
Configuring of HTTP modules is performed by using the webExtensions configuration section:
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <sectionGroup name="webMarkupMin"> <section name="core" type="WebMarkupMin.Core.Configuration.CoreConfiguration, WebMarkupMin.Core" /> <section name="webExtensions" type="WebMarkupMin.Web.Configuration.WebExtensionsConfiguration, WebMarkupMin.Web" /> … </sectionGroup> … </configSections> … <webMarkupMin xmlns="http://tempuri.org/WebMarkupMin.Configuration.xsd"> … <webExtensions enableMinification="true" disableMinificationInDebugMode="true" enableCompression="true" disableCompressionInDebugMode="true" maxResponseSize="100000" /> … </webMarkupMin> … </configuration>
Let's consider in detail properties of the webExtensions configuration section:
Property name | Data type | Default value | Description |
---|---|---|---|
enableMinification | Boolean | true | Flag for whether to enable markup minification. |
disableMinificationInDebugMode | Boolean | true | Flag for whether to disable markup minification during debugging. |
enableCompression | Boolean | true | Flag for whether to enable GZIP/Deflate compression of text content. |
disableCompressionInDebugMode | Boolean | true | Flag for whether to disable GZIP/Deflate compression of text content during debugging. |
maxResponseSize | Integer | 100 000 | Maximum size of the response (in bytes), in excess of which disables the minification of markup. |
These configuration settings are also used by other modules of the WebMarkupMin: WebMarkupMin.Mvc and WebMarkupMin.WebForms.
Because HTTP modules do not support caching, it is not recommended to use them for high-loaded sites.
WebMarkupMin.Mvc contains 4 classes of action filters:
Here is a simple example of usage of the action filters:
namespace WebMarkupMin.Example.Mvc.Controllers { using System.Web.Mvc; using Infrastructure.ActionResults; using WebMarkupMin.Mvc.ActionFilters; public class HomeController : Controller { [CompressContent] [MinifyHtml] [OutputCache(CacheProfile = "CacheCompressedContent5Minutes")] public ActionResult Index() { … } … [CompressContent] [MinifyXhtml] [OutputCache(CacheProfile = "CacheCompressedContent5Minutes")] public ActionResult Contact() { … } [CompressContent] [MinifyXml] [OutputCache(CacheProfile = "CacheCompressedContent5Minutes")] public SitemapResult Sitemap() { … } } }
Because markup minification and GZIP/Deflate compression require time and server resources, then we cache the result of their work by using OutputCacheAttribute.
WebMarkupMin.WebForms contains 3 classes of Web Forms pages:
Below is an example of usage one of these classes:
namespace WebMarkupMin.Example.WebForms { using System; using WebMarkupMin.WebForms.Pages; public partial class Contact : MinifiedAndCompressedHtmlPage { … } }
To disable the markup minification and GZIP/Deflate compression during the page postback, you can use the EnableMinification and EnableCompression page properties:
private void Page_PreLoad(object sender, EventArgs e) { if (IsPostBack) { EnableMinification = false; EnableCompression = false; } }
Result of the markup minification and GZIP/Deflate compression is recommended to cache by using the OutputCache directive:
<%@ Page Title="Contact" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Contact.aspx.cs" Inherits="WebMarkupMin.Example.WebForms.Contact" %>
<%@ OutputCache CacheProfile="CacheCompressedContent5Minutes" VaryByParam="*" %>
…
In addition, WebMarkupMin.WebForms contains 3 classes of master pages:
Below is an example of usage one of these classes:
namespace WebMarkupMin.Example.WebForms { using System; using System.Web.UI; using WebMarkupMin.WebForms.MasterPages; public partial class Site : MinifiedAndCompressedHtmlMasterPage { … } }
Сlasses of the Web Forms pages and master pages cannot be used together.