Web Compression: Code Minification
Introduction
Have you ever wondered how styling and client-side code is compressed? One way to accomplish this is with minification. The term is derived from the word minimizing; it is a small description into what the process actually is. Minimizing is essentially the process of removing unused/unnecessary spacing or control characters (i.e. line breaks) to save on the data required for a transfer. The best part about minification is that it can be done to virtually any web language: from CSS (Cascading Style Sheets), to HTML (Hyper Text Markup Language) and JS (JavaScript), minification can offer a noticeable performance boost with larger files.
Example of Minifying
With the following page, the process of “minimizing” can be demonstrated:
index.html
:
<!DOCTYPE html>
<html>
<head>
<title>Test Website</title>
<script src=”test.js” type=”text/javascript”></script>
</head>
<body>
<h1>Hello, world!</title>
<p>If JavaScript is working, <span id=”flag”>I’ll be changed!</span></p>
</body>
</html>
The test.js
specified in the HTML <head>
block:
function test() {
document.getElementById("flag").innerText = “then we’ll be having a great day!”;
}
if (document.readyState == “complete”) {
test();
}
First, we’ll begin by minifying our index.html
page:
<!DOCTYPE html><html><head><title>Test Website</title><script src=”test.js” type=”text/javascript”></script></head><body><h1>Hello, world!</title><p>If JavaScript is working, <span id=”flag”>I’ll be changed!</span></p></body></html>
Notice how all unnecessary spacing has been removed, while spaces within our paragraph block have been preserved (we cannot “remove” these spaces, otherwise the page would be rendered differently).
Finally, with our test.js
file:
function test(){document.getElementById("flag").innerText=“then we’ll be having a great day!”} if(document.readyState==“complete”){test()}
The difference here is (obviously) not large, but, with unnecessary spacing and control characters removed on a JS file of, say, 10K lines, there could be a potential savings of hundreds of kilobytes (which is a free boost of load performance without needing to optimize each line of code manually).