This article is part of a series created in partnership with SiteGround. Thank you for supporting the partners who make SitePoint possible.
Minifying a resource means getting rid of redundant elements, that is, elements which the browser doesn’t need in order to process the document correctly.
Applying this concept to a HTML document, minification could include things like:
- Removing unnecessary quotes, empty attributes, etc.
- Getting rid of CDATA sections
These operations contribute to keep the file size down, but also make it easier to keep the code clean and maintainable.
GZipping Versus Minifying Resources
Is still worth minifying HTML if you’re using GZip?
One of the arguments against HTML minification is that, gzipping HTML pages already gets rid of white space and reduces file size. This makes minification quite useless.
Firstly, it’s important to point out that the two operations are not the same and don’t achieve the same results.
The result of minification creates a file made of perfectly valid code that the browser can parse and execute, just like the unminified version of the same file. On the other hand,
Gzipping finds all repetitive strings and replaces them with pointers to the first instance of that string. … On the web, gzipping is done directly by your server. … The server compresses the file and sends it across the network like that. The browser receives the file and unzipped it before using it.
Chris Coyer on CSS Tricks
That said, using both techniques can make you save a few bytes. For instance, in Effects of GZipping vs. minifying HTML files, Mads Kristensen discusses a small experiment consisting of both minifying and gzipping the HTML files of four popular websites, i.e., amazon.com, cnn.com, twitter.com and xbox.com. The results show that by undergoing both gzipping and minification, the file size decreases by 9-16%.
The following tools will automate the minification process for you.
Minimize is an open source, server-side HTML5 minifier based on the node-htmlparser2.
- Can minify HTML5 code (not older HTML drafts, no inline PHP code or template files)
- It’s highly configurable
- Can distinguish conditional IE comments
… and more. You can visit the project page on GitHub for more details.
Will Peavy’s HTML Minifier
The HTML Minifier is an online tool for HTML minification built with PHP.
Kangax HTML Minifier
These are just some of this tool’s capabilities:
- Removing HTML comments
- Removing comments from styles and scripts
- Removing CDATA sections
- Removing attributes’ quotes
- Removing unnecessary attributes
- Removing blank attributes
- Validating input through HTMLLint
You can configure each option according to your own needs.
In this article, I’ve listed three tools that can help you shave a few bytes off of your web pages by automating a number of HTML minification tasks.
What about you, do you think minifying HTML is a good idea? What’s your favorite HTML minification tool?