Unpacking the Magic of Web Minification

Web minification is the process of removing unnecessary characters and whitespace from code used in web development, such as HTML, CSS, and JavaScript files. The minified file version provides the same functionality while reducing the bandwidth of network requests, which can result in faster page load times and better overall user experience.

Minification can include removing comments, reducing the length of variable and function names, and removing whitespace and line breaks. This process can be done manually, but it is more commonly automated as a build step in web bundlers.

How minifier works

Minifiers work by analyzing and modifying code to reduce its size while still preserving its functionality. Here are the basic steps that a minifier typically takes:

  1. Remove whitespace and comments: If you want to minify the code manually, you can start by removing whitespace and comments. These characters are not necessary for the code to function and can safely be removed.
  2. Use shorter variable names: The amount of characters required to represent the variable is reduced, and as a result, the size of the code is also reduced. This will make the code harder to read and understand for humans. However, minifiers are primarily concerned with reducing the size of the code, not making it easier to read.
  3. Use shorthand syntax: By replacing longer syntax with shorter and equivalent alternatives, especially shorthand syntax: object property shorthand, ternary operator shorthand, arrow function shorthand, array spread operator shorthand, or template literal shorthand.
  4. Removing unused code: The minifier can analyze the code to identify and remove unused variables, functions, and code blocks. This can further reduce the size of the code and improve its performance.
  5. Concatenate multiple files: If you have multiple JavaScript or CSS files, you can concatenate them into one file. This reduces the number of HTTP requests needed to download the code and improves the performance of your website.
  6. Use abbreviations: You can use abbreviations for CSS class names and IDs to reduce the size of your code. For example, instead of using “header” as a class name, you can use “hdr”.
  7. Remove optional tags: HTML allows for optional closing tags, such as </li> and </p>. You can remove these optional tags to reduce the size of your code.

There are more advanced techniques might be easer for a complier than a minifier:

  • Dead-code elimination within function bodies
  • Function inlining
  • Cross-statement constant propagation
  • Object shape modeling
  • Allocation sinking
  • Method devirtualization
  • Symbolic execution
  • JSX expression hoisting
  • TypeScript enum detection and inlining

The format of a minified version depends on the type of code being minified (e.g. HTML, CSS, JavaScript, etc.) and the specific minifier being used. However, in general, a minified version is a compressed and optimized version of the original code, with most of the unnecessary elements removed or reduced.

JavaScript Minifiers

JavaScript minification is a commonly used optimization technique in web development, and is often implemented in bundlers such as webpack, Rollup, and Parcel. Once the JavaScript code has been bundled, the bundler applies a minification step to further optimize the code. To aid with debugging, the bundler may also generate a source map file, which maps the minified code back to the original source code.

JavaScript libraries often provide minified versions of their files for production deployments, usually denoted with a min.js name extension.

Here’s an example of minifying JavaScript code using UglifyJS:

function square(x) {
  return x * x;
}

let num = 5;
let result = square(num);
console.log(result);

let message = "Hello, world!";
console.log(message);

let arr = [1, 2, 3, 4];
arr.forEach(num => console.log(num));

if (num > 3) {
  console.log("Number is greater than 3.");
} else {
  console.log("Number is less than or equal to 3.");
}

As you can see, the minified version of the code is much more condensed and harder to read. However, it also takes up much less space and can be loaded and executed more quickly by web browsers.

function square(n){return n*n}let e=5,t=square(e);console.log(t);let l="Hello, world!";console.log(l);let r=[1,2,3,4];r.forEach(n=>console.log(n)),console.log(e>3?"Number is greater than 3.":"Number is less than or equal to 3.")

CSS Minifiers

These are popular and widely used CSS minifiers that can be used to remove unnecessary whitespace, comments, and properties from CSS code. They may have an option for obfuscating class and ID names, which can help you further reduce the size of your CSS files.

This is an example of CSS before minification:

html {
  font-size: 16px;
  font-weight: 400;
  font-family: var(--font-normal);
  font-feature-settings: 'cv02', 'cv03', 'cv04', 'cv11';
  /* -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-rendering: optimizeLegibility; */
}

and this is minified CSS output:

html{font-size:16px;font-weight:400;font-family:var(--font-normal);font-feature-settings:'cv02','cv03','cv04','cv11'}

HTML Minifiers

These are popular and widely used HTML minifiers that can be used to remove unnecessary whitespace, comments, and attributes from HTML code.

This is an example of HTML before minification:

<!DOCTYPE html>
<html>
	<head>
		<title>My Website</title>
	</head>
	<body>
		<h1>Welcome to my website!</h1>
		<p>This is an example paragraph.</p>
		<ul>
			<li>Item 1</li>
			<li>Item 2</li>
			<li>Item 3</li>
		</ul>
	</body>
</html>

and minified output after using html-minifier:

<!DOCTYPE html><html><head><title>My Website</title></head><body><h1>Welcome to my website!</h1><p>This is an example paragraph.</p><ul><li>Item 1</li><li>Item 2</li><li>Item 3</li></ul></body></html>

Similar to obfuscation

Minification can be distinguished from the more general concept of data compression and code obfuscation.

Obfuscation is the practice of intentionally making code or data difficult to understand or read, while still preserving its functionality. The purpose of obfuscation is to deter reverse engineering, protect intellectual property, or prevent unauthorized access to sensitive information.

In the context of software development, obfuscation is often used to protect proprietary algorithms, licensing mechanisms, or digital rights management (DRM) systems. By obfuscating the code, the original program logic can be hidden, making it harder for an attacker to understand or modify it.

Obfuscation techniques can include renaming variables, functions, or classes to meaningless names, splitting code into multiple files, adding irrelevant code or comments, or encrypting strings and other data. However, obfuscation does not provide absolute security and can be circumvented by skilled attackers with enough time and resources.

It is important to note that obfuscation should not be confused with encryption, which is a process of converting data into a secret code to protect its confidentiality. Obfuscation, on the other hand, is not designed to protect data, but rather to make it harder to understand or modify code.