Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ 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.0] - 2026-11-20

### Fixed

* Fixed `partialMarkup` failing on a stray `</svg>` or `</math>` end tag (e.g., `</svg><svg><rect/></svg>` threw “Cannot read properties of undefined”)

### Changed

* Changed `collapseWhitespace` to keep whitespace at either end of `partialMarkup` fragments as a single space (or line break, with `preserveLineBreaks`) where it may separate the fragment from what surrounds it, as next to text, inline elements, and elements that don’t render (previously, ` <b>Jane</b>\n` became `<b>Jane</b>`, and `a <link rel="x">` became `a<link rel="x">`), while it still goes next to block elements
* Made pages with inline SVG or MathML faster to minify, as the first `svg` or `math` element slowed down the minification of the rest of the page (by 10–20% on pages without much SVG or MathML)

## [5.3.1] - 2026-11-19
Expand Down
10 changes: 8 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ Where the modifiers disagree, the preserving one wins—`conservativeCollapse` a

`collapseWhitespace` goes by the element, not by CSS, so whitespace in an element styled `white-space: pre` collapses unless you protect it with [`canCollapseWhitespace` and `canTrimWhitespace`](#api-only-options).

Regardless of these options, whitespace at the start and end of the output goes, and so do lines that a removed comment or tag leaves with nothing but whitespace (blank lines of the source stay). Whitespace stays, however, where it’s kept verbatim (in `pre` or `textarea`, or in `pre`, `textarea`, or `script` content left open at the end), next to custom fragments where their handling keeps it (see `trimCustomFragments`), at either end of partial markup (cf. `partialMarkup`), and where `conservativeCollapse` or `preserveLineBreaks` keep it.
Regardless of these options, whitespace at the start and end of the output goes, and so do lines that a removed comment or tag leaves with nothing but whitespace (blank lines of the source stay). Whitespace stays, however, where it’s kept verbatim (in `pre` or `textarea`, or in `pre`, `textarea`, or `script` content left open at the end), next to custom fragments where their handling keeps it (see `trimCustomFragments`), at either end of partial markup (cf. `partialMarkup`; `collapseWhitespace` collapses it there), and where `conservativeCollapse` or `preserveLineBreaks` keep it.

Note: `preserveLineBreaks` keeps line breaks, not indentation. HTML Minifier doesn’t format: To keep the source formatting, leave `collapseWhitespace` off (as in the first row of the table above). Line breaks and indentation then stay as written, while other options still apply.

Expand Down Expand Up @@ -707,7 +707,13 @@ By default, HM parses markup into a complete tree structure, then modifies it (r

_Input markup (e.g., `<p id="">foo`) → Internal representation of markup in a form of tree (e.g., `{ tag: "p", attr: "id", children: ["foo"] }`) → Transformation of internal representation (e.g., removal of `id` attribute) → Output of resulting markup (e.g., `<p>foo</p>`)_

For partial HTML fragments (such as template includes, SSI fragments, or closing tags without opening tags), use the `partialMarkup: true` option. This preserves stray end tags and prevents auto-closing of unclosed tags at the end of input. Note that normal HTML auto-closing rules still apply during parsing—for example, a closing parent tag will still auto-close its unclosed child elements, and an end tag browsers ignore because a block element is still open inside its element is removed (use `<!-- htmlmin:ignore -->` to keep such markup as written). Whitespace at the start and end of a fragment stays, too, as it may separate the fragment from what surrounds it (unless `collapseWhitespace` removes it). `removeRedundantAttributes` keeps `target="_self"` in partial markup, as there may be a `base` element setting another target elsewhere. (Where an external script adds such a `base` element, wrap links whose `target="_self"` needs to stay in `<!-- htmlmin:ignore -->`.)
For partial HTML fragments (such as template includes, SSI fragments, or closing tags without opening tags), use the `partialMarkup: true` option. This preserves stray end tags and prevents auto-closing of unclosed tags at the end of input. Note that normal HTML auto-closing rules still apply during parsing—for example, a closing parent tag will still auto-close its unclosed child elements, and an end tag browsers ignore because a block element is still open inside its element is removed (use `<!-- htmlmin:ignore -->` to keep such markup as written).

Whitespace at the start and end of a fragment stays, too, as it may separate the fragment from what surrounds it. `collapseWhitespace` collapses it to a space (or line break, with `preserveLineBreaks`) where text in its place would keep one, as next to text and inline elements, and removes it next to block elements (e.g., with `␣` marking a space, `␣<b>Jane</b>\n` becomes `␣<b>Jane</b>␣`, while `\n<div>…</div>\n` becomes `<div>…</div>`).

With `removeOptionalTags`, end tags at the end of a fragment may be omitted (e.g., `<p>a</p>` becomes `<p>a`), so content following the fragment would end up inside those elements.

`removeRedundantAttributes` keeps `target="_self"` in partial markup, as there may be a `base` element setting another target elsewhere. (Where an external script adds such a `base` element, wrap links whose `target="_self"` needs to stay in `<!-- htmlmin:ignore -->`.)

Markup with [parse errors](https://html.spec.whatwg.org/multipage/parsing.html#parse-errors) that HM cannot read, like a stray `</>` or an `=` in an unquoted attribute value, makes it abort with the line and column of the error, so that the error can be fixed. With `continueOnParseError`, HM handles such errors the way browsers do instead.

Expand Down
18 changes: 9 additions & 9 deletions package-lock.json

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

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"entities": "^9.0.0",
"lightningcss": "^1.33.0",
"svgo": "^4.1.0",
"terser": "^5.51.2"
"terser": "^5.51.3"
},
"description": "Highly effective, super-configurable, well-tested web page minifier",
"devDependencies": {
Expand Down Expand Up @@ -98,5 +98,5 @@
},
"type": "module",
"types": "dist/types/htmlminifier.d.ts",
"version": "5.3.1"
"version": "5.4.0"
}
48 changes: 35 additions & 13 deletions src/htmlminifier.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import {
pClosingParents,
namesForeignMixedCase,
integrationPointsForeign,
processingInstructionTag,
MISSING_DEPENDENCY
} from './lib/constants.js';

Expand Down Expand Up @@ -973,6 +974,13 @@ function matchPlainEndTag(str) {
return str.slice(2, end - 1);
}

// At either end of partial markup, collapsed whitespace may separate the fragment from what
// surrounds it, and so stays where text in its place would keep it
/** @param {ProcessedOptions} options */
function keepsEdgeWhitespace(options) {
return Boolean(options.collapseWhitespace && options.partialMarkup && !options.conservativeCollapse);
}

/**
* @param {string} value
* @param {ProcessedOptions} options
Expand All @@ -985,7 +993,9 @@ async function minifyHTML(value, options, partialMarkup) {
throw new Error(`Input length (${value.length}) exceeds maximum allowed length (${options.maxInputLength})`);
}

if (options.collapseWhitespace) {
const keepsEdges = keepsEdgeWhitespace(options);

if (options.collapseWhitespace && !keepsEdges) {
value = collapseWhitespace(value, options, true, true);
}

Expand Down Expand Up @@ -1534,7 +1544,7 @@ async function minifyHTML(value, options, partialMarkup) {
const [, after] = findNeighbors(last.end + 1);
const textBefore = buffer[before] ?? '';
const textAfter = buffer[after] ?? '';
if (before < 0 || after >= buffer.length || RE_WS_END.test(textBefore) || RE_WS_START.test(textAfter)) {
if ((!keepsEdges && (before < 0 || after >= buffer.length)) || RE_WS_END.test(textBefore) || RE_WS_START.test(textAfter)) {
for (let i = gapFrom; i < gapTo; i++) bufferSet(i, '');
}
}
Expand Down Expand Up @@ -1949,7 +1959,8 @@ async function minifyHTML(value, options, partialMarkup) {
index--;
}
}
return false;
// What precedes partial markup may run into it, too
return keepsEdges;
}

// Per-text-node context for `charsCollapse`/`charsFinalize`, set by the `chars`
Expand Down Expand Up @@ -2046,7 +2057,10 @@ async function minifyHTML(value, options, partialMarkup) {
}
}
if (textPrevTag || textNextTag) {
let collapsed = collapseWhitespaceSmart(text, effectivePrevTag, textNextTag, textPrevAttrs, textNextAttrs, options, inlineSets, !stackNoCollapseWhitespace.length);
// Beyond an edge of partial markup, anything may render, as for a processing instruction
const smartPrevTag = keepsEdges && effectivePrevTag === '' ? processingInstructionTag : effectivePrevTag;
const smartNextTag = keepsEdges && textNextTag === '' ? processingInstructionTag : textNextTag;
let collapsed = collapseWhitespaceSmart(text, smartPrevTag, smartNextTag, textPrevAttrs, textNextAttrs, options, inlineSets, !stackNoCollapseWhitespace.length);
if (!transparentDepth && inlineElementsTransparentAfter.has(textPrevTag)) {
// Between elements that don’t render, whitespace stays pending when it may
// separate text, and one space does
Expand Down Expand Up @@ -2084,7 +2098,8 @@ async function minifyHTML(value, options, partialMarkup) {
}
}
} else {
text = collapseWhitespace(text, options, true, true);
// Raw text has no tag on either side, unlike an edge of partial markup
text = collapseWhitespace(text, options, !keepsEdges || textPrevTag !== '', !keepsEdges || textNextTag !== '');
}
if (!text && RE_TRAILING_WHITESPACE.test(currentChars) && textPrevTag && textPrevTag.charAt(0) === '/' && !holdTransparentGap(buffer.length - 1, textNextTag)) {
trimTrailingWhitespace(buffer.length - 1, textNextTag);
Expand Down Expand Up @@ -2995,15 +3010,16 @@ async function minifyHTML(value, options, partialMarkup) {
}
}
},
chars: function (/** @type {string} */ text, /** @type {string} */ prevTag, /** @type {string} */ nextTag, /** @type {HTMLAttribute[]} */ prevAttrs, /** @type {HTMLAttribute[]} */ nextAttrs, /** @type {boolean} */ source) {
chars: function (/** @type {string} */ text, /** @type {string} */ prevTag, /** @type {string} */ nextTag, /** @type {HTMLAttribute[]} */ prevAttrs, /** @type {HTMLAttribute[]} */ nextAttrs, /** @type {boolean} */ source, /** @type {boolean} */ first, /** @type {boolean} */ last) {
if (mergeRecord) {
if (mergeRecord.content === -1) mergeRecord.content = buffer.length;
// Custom fragments may hold anything, which minified CSS can’t take as written
if (mergeRecord.kind === 'style' && markers.length && markers.some(marker => text.includes(marker))) mergeRecord.key = null;
}
// Publish this node’s context for the `charsCollapse`/`charsFinalize` phases
textPrevTag = followsRemovedBlock ? charsPrevTag || 'comment' : prevTag === '' ? 'comment' : prevTag;
textNextTag = nextTag === '' ? 'comment' : nextTag;
// An edge of partial markup reads as no tag, so that whitespace there may stay
textPrevTag = followsRemovedBlock ? charsPrevTag || 'comment' : first && keepsEdges ? '' : prevTag === '' ? 'comment' : prevTag;
textNextTag = last && keepsEdges ? '' : nextTag === '' ? 'comment' : nextTag;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
textPrevAttrs = prevAttrs || [];
textNextAttrs = nextAttrs || [];

Expand Down Expand Up @@ -3103,7 +3119,7 @@ async function minifyHTML(value, options, partialMarkup) {

// Nothing follows at the end, so pending whitespace goes (before SVG blocks shift the buffer)
if (transparentGapIndex !== -1) {
settleTransparentGap(Boolean(options.conservativeCollapse));
settleTransparentGap(Boolean(options.conservativeCollapse) || keepsEdges);
}

if (mergeRecords && (mergeRecords.length > 1 || mergeRecords[0]?.deferred)) {
Expand Down Expand Up @@ -3144,14 +3160,16 @@ async function minifyHTML(value, options, partialMarkup) {
if (topLevelElements.has(optionalStartTag)) {
removeStartTag();
}
// Except for `</dt>` or `</thead>`, end tags may be omitted if no more content in parent
if (optionalEndTag && optionalEndTagEmitted && !trailingElements.has(optionalEndTag)) {
// Except for `</dt>` or `</thead>`, end tags may be omitted if no more content in parent;
// whitespace kept at the end of partial markup follows the tag, which then stays
if (optionalEndTag && optionalEndTagEmitted && !trailingElements.has(optionalEndTag) &&
!(keepsEdges && !RE_END_TAG.test(buffer[skipRun(runEmpty, buffer.length - 1)] ?? ''))) {
removeEndTag();
}
}
// Collapsing also trims whitespace before trailing inline end tags; trimming the output
// catches what it leaves at either end, like a space after a removed leading comment
if (options.collapseWhitespace) {
if (options.collapseWhitespace && !keepsEdges) {
squashTrailingWhitespace('br');
}
trimOutputWhitespace();
Expand Down Expand Up @@ -3264,7 +3282,11 @@ function joinResultSegments(results, resultTags, markers, options, restoreCustom
} else {
str = restoreIgnore(restoreCustom(results.join('')));
}
return options.collapseWhitespace ? collapseWhitespace(str, options, true, true) : str;
if (!options.collapseWhitespace) {
return str;
}
const trims = !keepsEdgeWhitespace(options);
return collapseWhitespace(str, options, trims, trims);
}

/**
Expand Down
5 changes: 3 additions & 2 deletions src/htmlparser.js
Original file line number Diff line number Diff line change
Expand Up @@ -808,8 +808,9 @@ export class HTMLParser {
}

if (handler.chars) {
// An element whose end tag follows its start tag’s text alone has that text for content
const result = handler.chars(text, prevTag, nextTag, prevAttrs, nextAttrs, sourcePos !== -1 && isSource(pos - text.length));
// An element whose end tag follows its start tag’s text alone has that text for content;
// the last two arguments say whether the text starts or ends the input
const result = handler.chars(text, prevTag, nextTag, prevAttrs, nextAttrs, sourcePos !== -1 && isSource(pos - text.length), pos === text.length, pos === fullLength);
if (isThenable(result)) await result;
}
prevTag = '';
Expand Down
Loading