Home / Blog / HTML & CSS

HTML & CSS

How To Compress HTML Source Code?

Minify HTML with conservative parser-based settings, verify whitespace and behaviour, then measure source size separately from HTTP compression.

How To Compress HTML Source Code?

To make HTML source smaller, use an HTML minifier that understands document syntax, then test the generated page. An HTML beautifier adds indentation for readability and is not a compression tool. Minification reduces source characters; HTTP gzip or Brotli compression reduces transferred bytes. These are separate operations, and enabling one does not prove that the other is working.

Start with conservative minification

Keep readable HTML in source control and generate a separate minified file during the build. One option is html-minifier-terser. Install it as a development dependency, lock the version in your project, and start with a small set of options. Most of its transformations are disabled by default. Avoid enabling every option at once: removing optional tags, rewriting embedded scripts and collapsing inline whitespace can each affect a different part of the document.

A reproducible Node.js example

const fs = require('node:fs/promises');
const { minify } = require('html-minifier-terser');

async function build() {
  const source = await fs.readFile('page.html', 'utf8');
  const result = await minify(source, {
    collapseWhitespace: true,
    conservativeCollapse: true,
    removeComments: false,
    minifyCSS: false,
    minifyJS: false
  });
  await fs.writeFile('page.min.html', result, 'utf8');
  console.log(Buffer.byteLength(source), Buffer.byteLength(result));
}
build().catch(error => { console.error(error); process.exitCode = 1; });

This configuration first concentrates on HTML whitespace. It leaves comments and embedded JavaScript/CSS alone. That makes it easier to attribute a regression to one transformation. The logged sizes are UTF-8 bytes, not JavaScript string lengths and not the compressed response size. Preserve the source file if a build fails; do not overwrite it with an empty or partially generated result.

Protect whitespace that carries meaning

Consider <span>red</span> <span>blue</span>. The space between the spans separates two words. Removing it can render “redblue”. Content in pre, textarea and code examples also needs care. Browser CSS can make whitespace significant in additional places, so a parser alone cannot prove that every visible layout is unchanged. Keep a sample with inline elements, multiline code and user-visible text in the regression set.

A general regular expression such as “replace all whitespace with one space” is not a safe HTML minifier. It can rewrite JavaScript strings, CSS values, template syntax or attribute contents. Do not remove every comment blindly either: some projects retain licence comments or use comments as processing markers. Decide which comments are safe to strip after inspecting the actual build pipeline.

Test the generated document, not just its size

Open the original and minified files through the same local server. Compare visible headings, paragraph text, links, form submission, keyboard navigation and any embedded script behaviour. Exercise responsive layouts at the widths your site supports. Check the browser console for new errors and inspect requests for missing files. If the page uses client rendering, hydration or a template framework, also test the framework's production path.

A useful fixture includes a title with an ampersand, quoted attributes, an inline pair of words, a preserved code block, a form field and a script that changes a label after a click. The minified page should preserve all of those behaviours. A reduced byte count only measures size; it does not establish semantic equivalence. Keep automated assertions for the parts of the page that matter to users, alongside a visual comparison where layout is significant.

Measure transfer compression separately

After deploying through your normal authorized process, inspect the actual response's Content-Encoding and transferred size in browser developer tools. A minified file may already compress efficiently, so percentage savings from two stages are not additive. Compare the same resource with the same cache state and request conditions. Preserve readable development assets and source maps according to your publication policy, rather than distributing only an irreversible minified source copy.

The site's HTML formatter is useful when you want readable indentation for inspection. Use a minifier for reducing HTML size, a formatter for readability, and a validator to find structural errors. Neither formatting nor minification corrects incorrect markup automatically. For embedded JavaScript, test a JavaScript-aware minifier separately; changing identifiers or expressions deserves its own regression checks.

Primary references