In Part 1, we looked at server side compression and how it can reduce the overall size of a web page. The web page can be further optimised by minification, a process whereby all unnecessary characters are stripped from a file.
Let’s look at an example:
<!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8"> <title>Minification</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <!-- Add your site or application content here --> <p>This is an article about minification.</p> </body> </html>
The code in Figure 1 is indented and split across several lines. Much like the sentences and paragraphs in an article, this is done to increase legibility. This is useful during development, when the developer is writing the code. However, since the code is not seen by the users who view the web page, code readability is of little importance to them. Armed with this knowledge, we can confidently minify our files before deployment.
The code above is 329 bytes in length. What can be stripped? Each of the 13 lines, with the exception of the last line, contains an invisible character that marks the end of line ( EOL ). That’s 12 EOL characters, totalling 12 bytes. 329 - 12 = 317 bytes.
There are 28 indentation spaces, totalling 28 bytes. 317 - 28 = 289 bytes.
The start and end of a comment are marked by the opening and closing tags, <!– –>
Since comments are not visible when a web page is viewed, they can safely be stripped. Line 10 is a comment, 50 bytes in length. 289 - 50 = 239 bytes.
Our code now looks this:
<!doctype html><html class="no-js" lang="en"><head><meta charset="utf-8"><title>Minification</title><meta name="viewport" content="width=device-width, initial-scale=1"></head><body><p>This is an article about minification.</p></body></html>
The code is now 239 bytes in length, down from 329 bytes. A 27.36% reduction.
Figure 3 shows the effect of minification on a web page. The test setup was introduced in Part 1. Google Chrome’s Developer Tools, bandwidth throttled to Regular 3G.
* fontfaceobserver.min.js is already minified, hence the .min extension in its name.
Minification results in a web page that is 16.19% smaller, and loads 14.22% more quickly.
I use Grunt, an offline build tool that automates a lot of web development tasks. It is quicker and less error prone than doing things manually.
The following Grunt plugins handle the minification of specific file types:
grunt-contrib-htmlmin - HTML files, .html .shtml
grunt-contrib-sass - CSS files, .css
grunt-svgmin - SVG files, .svg