How to Minify CSS and JavaScript

How to Minify CSS and JavaScript

You’ve seen it: a CSS file that’s one 40-kilobyte line with no spaces. That’s minified code — identical behavior, smaller file. And smaller files load faster.

What minification does

Minifiers remove everything the browser doesn’t need to execute the code:

  • Whitespace, indentation, and line breaks
  • Comments
  • Semicolons where the grammar makes them optional
  • Long variable names, sometimes shortened (in JS)

Nothing about the behavior changes — which is the point. The code is for the machine now, not for humans.

The size math

Typical savings: 20–30% for CSS, 30–50% for JavaScript, before gzip. Combined with compression, a 100 KB JS file can ship as ~30 KB over the wire. On slow connections and mobile, that’s the difference between a page that feels instant and one that feels broken.

The workflow

  1. Keep readable, commented source files in your project — minify at build/deploy time, never edit minified files.
  2. Use the CSS minifier and JS minifier to produce production versions.
  3. If you ever receive a minified file and need to read it, the same tools work in reverse — unminify restores indentation and readability (comments are gone for good, though).

Don’t skip the obvious

  • Source maps: when minifying JS, generate source maps so error reports point to your real code, not line 1 of a minified blob.
  • Cache headers: minified files change on every deploy; make sure your hosting serves them with proper cache busting (hashed filenames are standard).
  • Don’t hand-edit minified output: a typo in minified code is nearly impossible to find. Edit the source, minify again.

Minification is the cheapest performance win available — no code changes, no redesign, just smaller files.