Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,19 @@ As of version 5.0.0, all notable changes to HTML Minifier (HM) are documented in

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and the project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]
## [5.4.1] - 2026-11-22

### Fixed

* Fixed `minifyJS` breaking scripts where a custom fragment starts a statement after a label or `case` the fragment check missed—after a template literal holding a backtick (``var s = `${"`"}`; l: <?= $x ?>;`` became ``var s="`";b(), <?= $x ?>``), after a label with a non-ASCII name, and after a label within a block (`switch (a) { case 1: { l: <?= $x ?> } }`)—by parsing JavaScript with Acorn rather than reading it by hand
* Fixed `minifyCSS` and `minifyJS` changing the quotes around custom fragments in strings; such code now stays as written
* Fixed `minifyJS` doubling whitespace next to custom fragments in strings that Terser escapes (e.g., a tab before `<?= $x ?>` in a string became `\t` and the tab)
* Fixed `minifyJS` rewriting escapes right before custom fragments in strings into ones the rendered fragment could extend (`"\x00<?= $x ?>"` became `"\0<?= $x ?>"`, which reads differently before a digit); such code now stays as written
* Fixed `minifyCSS` reading escaped quotes (`x\"`) as the start of a string when checking custom fragments

### Changed

* Made minification faster by checking short attribute and class lists for repeats without building a set
* Changed the backtest’s user agent to `html-minifier-backtest (+https://github.com/j9t/html-minifier/tree/main/backtest)`, dropping the placeholder version and adding a URL

## [5.4.0] - 2026-11-20
Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -735,7 +735,9 @@ HTML reads CRLF and CR line breaks as line feeds, so HM writes them so, too. Mar

By default, `ignoreCustomFragments` preserves `<?php … ?>`, `<?= … ?>`, `<? … ?>`, and `<% … %>` blocks (as well as XML declarations), so PHP, ERB, JSP, and ASP templates can be minified as part of a build, with the markup, CSS, and JavaScript around those blocks being minified as usual. For includes and other partials, add `partialMarkup`.

CSS and JavaScript are only left as written where a template block starts a rule or statement (`<?php if ($a): ?>` between two statements, `<?= $rules ?>` after a rule, or `<?= $code ?>` after `case 1:`, `default:`, or a label), as it may render as anything or as nothing, or where it sits in an `@charset`, `@import`, or `@namespace` statement that would otherwise be dropped with it (`@import <?= $url ?>;`). Template blocks within values (`color: <?= $color ?>`) are safe—here, the code around them is minified, so a block in code that minification removes (such as an unused rule or dead code) goes with that code. This detection is best-effort, as HTML Minifier doesn’t parse template code. To exempt anything it misses, use [`canMinifyCSS`](#css-minification) or [`canMinifyJS`](#javascript-minification).
CSS and JavaScript are only left as written where a template block starts a rule or statement (`<?php if ($a): ?>` between two statements, `<?= $rules ?>` after a rule, or `<?= $code ?>` after `case 1:`, `default:`, or a label), as it may render as anything or as nothing, or where it sits in an `@charset`, `@import`, or `@namespace` statement that would otherwise be dropped with it (`@import <?= $url ?>;`). They’re also left as written where minifying would move a template block into another kind of string (Terser and Lightning CSS turn `'<?= $name ?>'` into `"<?= $name ?>"`, which breaks if the value is escaped for single quotes only), repeat it, or change the whitespace around it within a string, and JavaScript is left as written where it doesn’t parse with the template blocks in it.

Template blocks within values (`color: <?= $color ?>`) are safe—here, the code around them is usually minified, so a block in code that minification removes (such as an unused rule or dead code) goes with that code. In CSS, that takes the block being on the same line as the value: After a line break, it may start a rule, so CSS around it stays as written. In JavaScript, a block in code is minified as if it were one value, so it should render as one—a literal, JSON, or an expression in parentheses: `if (a) { return <?= $x ?>; } return false` becomes `return!!a&& <?= $x ?>`, which a block rendering `1 || 2` would turn into `(!!a && 1) || 2`. This detection is best-effort: HTML Minifier parses JavaScript (with [Acorn](https://github.com/acornjs/acorn)), but not the template code itself. To exempt anything it misses, use [`canMinifyCSS`](#css-minification) or [`canMinifyJS`](#javascript-minification).

Whitespace next to template blocks is collapsed but kept, as it may matter once the template renders. `trimCustomFragments` removes it where HTML Minifier would remove whitespace anyway, as between block-level elements: `<ul> <?php foreach ($items as $item): ?> <li>` loses it, `Hello <?= $name ?>!` keeps it. Tags keep the spacing of their source, and whitespace next to template blocks in attribute values, CSS, and JavaScript is always kept.

Expand Down
4 changes: 2 additions & 2 deletions backtest/benchmark-ab.js
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ async function main() {
const labelB = args.aa ? `${args.ref} (copy)` : 'working tree';

console.log(`A: ${args.ref} @ ${commit}; B: ${labelB}`);
console.log(`* ${files.length} file(s), ${args.pairs} pair(s) of runs in both orders, fastest of ${args.rounds} round(s) per file`);
console.log(`• ${files.length} file(s), ${args.pairs} pair(s) of runs in both orders, fastest of ${args.rounds} round(s) per file`);

try {
extractRef(args.ref, dirA);
Expand All @@ -193,7 +193,7 @@ async function main() {
const mean = sum(pcts) / pcts.length;
console.log(`collapseWhitespace ${mode}: B−A ${formatPct(mean)} (runs from ${formatPct(Math.min(...pcts))} to ${formatPct(Math.max(...pcts))})`);
const changed = bytes.filter(delta => delta !== 0).length;
console.log(`* Output: ${changed ? `${changed} file(s) differ, ${sum(bytes).toLocaleString('en-US')} bytes in total` : 'identical'}`);
console.log(`• Output: ${changed ? `${changed} file(s) differ, ${sum(bytes).toLocaleString('en-US')} bytes in total` : 'identical'}`);
const rows = files.map((name, i) => ({ name, delta: deltas[i], bytes: bytes[i] }))
.sort((x, y) => Math.abs(y.delta) - Math.abs(x.delta))
.slice(0, args.top);
Expand Down
6 changes: 3 additions & 3 deletions backtest/benchmark.js
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ async function main({ argv = process.argv.slice(2), dirWork = __dirname } = {})

const modes = [args.core ? 'core: external minifiers disabled' : '', args.cold ? 'cold: caches off, so CSS/JS/SVG work is redone every iteration' : ''].filter(Boolean);
console.log(`Benchmarking ${fileNames.length} file(s)${modes.length ? ' (' + modes.join('; ') + ')' : ''}, fastest of ${args.iterations} iteration(s)`);
console.log(`* Options: ${args.preset ? `preset “${args.preset}”` : args.config}; compressed with Gzip level ${GZIP_LEVEL} and Brotli quality ${BROTLI_QUALITY}`);
console.log(`• Options: ${args.preset ? `preset “${args.preset}”` : args.config}; compressed with Gzip level ${GZIP_LEVEL} and Brotli quality ${BROTLI_QUALITY}`);

const compareCompressed = compressionComparable(baseline);

Expand All @@ -315,10 +315,10 @@ async function main({ argv = process.argv.slice(2), dirWork = __dirname } = {})

const mismatches = baselineMismatches(baseline, args);
if (mismatches.length) {
console.log(`* Warning: Baseline settings differ (${mismatches.join('; ')})—deltas may not be comparable`);
console.log(`• Warning: Baseline settings differ (${mismatches.join('; ')})—deltas may not be comparable`);
}
if (!compareCompressed) {
console.log('* Note: Baseline has no compressed sizes at these levels—re-run with `--save` to compare them');
console.log('• Note: Baseline has no compressed sizes at these levels—re-run with `--save` to compare them');
}
}
console.log('');
Expand Down
31 changes: 16 additions & 15 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@
},
"bugs": "https://github.com/j9t/html-minifier/issues",
"dependencies": {
"acorn": "^8.19.0",
"commander": "^15.1.0",
"entities": "^9.0.0",
"lightningcss": "^1.33.0",
"svgo": "^4.1.0",
"terser": "^5.51.3"
"terser": "^5.51.4"
},
"description": "Highly effective, super-configurable, well-tested web page minifier",
"devDependencies": {
Expand Down Expand Up @@ -98,5 +99,5 @@
},
"type": "module",
"types": "dist/types/htmlminifier.d.ts",
"version": "5.4.0"
"version": "5.4.1"
}
1 change: 1 addition & 0 deletions site/default.css
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ i,

i {
font-style: normal;
outline: 1px solid var(--color-accent);
}

code,
Expand Down
10 changes: 7 additions & 3 deletions src/htmlminifier.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ import {

import { declinesMinify, processOptions } from './lib/options.js';
import { canScriptFollow, canStyleSheetsJoin, getMergeKey, holdsHashbang, joinScripts, joinStyleSheets } from './lib/merging.js';
import { toFragment, replaceCustomFragments, isMinifiedCodeSafe } from './lib/fragments.js';
import { toFragment, replaceCustomFragments, isMinifiedCSSSafe, isMinifiedJSSafe } from './lib/fragments.js';

/** @import { ProcessedOptions } from './lib/options.js' */

Expand Down Expand Up @@ -1208,11 +1208,15 @@ async function minifyHTML(value, options, partialMarkup) {
return (chunks?.[1] ?? '') + uidAttr + index + uidAttr + (chunks?.[2] ?? '');
});
const result = fn(source, ...args);
const finish = (/** @type {string} */ output) => {
if (isMinifiedCodeSafe(source, output, uidPlaceholderPattern, isJS)) return output;
const settle = (/** @type {string} */ output, /** @type {boolean} */ isSafe) => {
if (isSafe) return output;
options.log('Keeping CSS or JavaScript as written, as minifying could break or lose a custom fragment');
return source;
};
// `args` are the inline and module flags `minifyJS` is called with
const finish = (/** @type {string} */ output) => isJS
? isMinifiedJSSafe(source, output, uidPlaceholderPattern, Boolean(args[0]), Boolean(args[1])).then(isSafe => settle(output, isSafe))
: settle(output, isMinifiedCSSSafe(source, output, uidPlaceholderPattern));
return isThenable(result) ? Promise.resolve(result).then(finish) : finish(result);
};

Expand Down
29 changes: 26 additions & 3 deletions src/lib/attributes.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,15 +137,29 @@ function deduplicateAttributes(attrs, caseSensitive) {
return attrs;
}

// Most tags hold a few attributes, which are faster compared with each other than in a set
const keys = attrs.map(attr => caseSensitive ? attr.name : attr.name.toLowerCase());
let hasDuplicates = false;
if (keys.length <= 8) {
for (let i = 1; i < keys.length && !hasDuplicates; i++) {
hasDuplicates = keys.lastIndexOf(/** @type {string} */ (keys[i]), i - 1) !== -1;
}
} else {
hasDuplicates = new Set(keys).size !== keys.length;
}
if (!hasDuplicates) {
return attrs;
}

const seen = new Set();
let writeIndex = 0;

for (const attr of attrs) {
const key = caseSensitive ? attr.name : attr.name.toLowerCase();
for (let i = 0; i < attrs.length; i++) {
const key = keys[i];

if (!seen.has(key)) {
seen.add(key);
attrs[writeIndex++] = attr;
attrs[writeIndex++] = /** @type {HTMLAttribute} */ (attrs[i]);
}
}

Expand Down Expand Up @@ -786,6 +800,15 @@ function dedupeClassNames(value) {
return value;
}
const names = value.split(RE_ATTR_WS_COLLAPSE);
// As with attributes, a short list is faster checked name by name than through a set
if (names.length <= 16) {
for (let i = 1; i < names.length; i++) {
if (names.lastIndexOf(/** @type {string} */ (names[i]), i - 1) !== -1) {
return [...new Set(names)].join(' ');
}
}
return value;
}
const unique = new Set(names);
return unique.size === names.length ? value : [...unique].join(' ');
}
Expand Down
Loading