Minification
In computer science, minification is the process of removing unnecessary elements and rewriting code to reduce file size. It is commonly done to web page resources, such as HTML, CSS, and JavaScript files. Reducing the size of web resources allows the files to be transferred more quickly, making web pages load faster.
There are several ways to minify data. The most basic is to remove comments, unnecessary spaces, and line breaks (newline characters). While comments and whitespace help make the code more readable, they are ignored by the browser. Therefore these elements can be safely removed before publishing. Another method is to minimize the code required for each statement. In CSS, this is often accomplished by converting longhand CSS to shorthand CSS. For example, a margin definition might take seven lines in longhand, but only one line in shorthand. In JavaScript, long variable names can be replaced with shorter ones (often a single character.
Below is an example of CSS code before and after minification. Note how the comments, spaces, line breaks, and unnecessary semicolons are removed. The code is also converted from longhand CSS to shorthand.
Standard CSS code
img.left /* float left 400px image */
{
float: left;
max-width: 400px;
margin-top: 8px;
margin-right: 30px;
margin-bottom: 12px;
margin-left: 0px;
}
Minified CSS code
img.left{float:left;max-width:400px;margin:8px 30px 12px 0}
Advanced minification algorithms can reduce file size even further. A CSS minifier, for instance, may find and remove duplicate lines within a CSS file. It may also combine similar CSS definitions into a single statement. A JS minifier may actually rewrite JavaScript functions to be more efficient.
Minifying code often saves only a few kilobytes. For example, a standard CSS file may be 50KB and the minified version may be 40KB. However, when improving page load speed, every kilobyte matters. The goal of a good minifier is to reduce file size as much as possible with zero impact on the way the code is parsed or processed. Regardless of what minifier is used, developers typically maintain a non-minified version of the code for future editing.
Minification vs Compression
While minification and file compression both reduce file size, they are not identical. Minification simply alters the text while file compression completely rewrites the binary code within a file. A compressed file must be decompressed by file decompression utility in order to be read as a text file. Many websites use a combination of minification and "gzip" file compression to reduce the size of web resources as much as possible.