Last updated
HTML Minification Explained
HTML minification removes unnecessary characters from HTML source code without changing its functionality. The goal is to reduce file size to improve page load speed. A typical HTML file can be reduced by 10–30% through minification alone. Combined with gzip compression (which web servers apply automatically), the savings are even greater — gzip works better on repetitive text, and minified HTML is more repetitive.
Safe vs Aggressive Minification
| Technique | Safety | Savings |
|---|---|---|
| Remove HTML comments | Safe | Medium |
| Collapse whitespace | Safe (mostly) | High |
| Remove optional tags | Safe per spec | Low |
| Minify inline CSS | Safe | Medium |
| Minify inline JS | Safe | High |
| Remove attribute quotes | Risky | Low |
| Remove boolean attributes | Safe per spec | Low |
Minification in a Build Pipeline
// Vite automatically minifies HTML in production builds
// vite.config.js
import { defineConfig } from 'vite';
export default defineConfig({
build: {
minify: true, // minifies JS/CSS
// HTML is minified by default in production
}
});
// For static sites, use html-minifier-terser in a build script:
import { minify } from 'html-minifier-terser';
import { readFile, writeFile, readdir } from 'fs/promises';
import path from 'path';
async function minifyHtmlFiles(dir) {
const files = (await readdir(dir)).filter(f => f.endsWith('.html'));
for (const file of files) {
const content = await readFile(path.join(dir, file), 'utf8');
const minified = await minify(content, {
collapseWhitespace: true,
removeComments: true,
minifyCSS: true,
minifyJS: true
});
await writeFile(path.join(dir, file), minified);
console.log(`${file}: ${content.length} → ${minified.length} bytes`);
}
}