コンテンツへスキップ
uencoder

HTML をミニファイする方法

空白・コメント・冗長な属性を取り除いて HTML ファイルサイズを削減します。

问题

ページの読み込みを速くするために、HTML ファイルサイズを削減する必要があります。

前提条件

  • HTML 構造の理解
  • 空白文字の意味に関する知識

ステップ

  1. 1. Identify safe-to-remove content

    Whitespace between block-level tags, HTML comments, and redundant attributes (like type='text' on script tags) can be removed. However, whitespace in <pre> tags and inline elements with display:inline may be significant.

    入力
    <div>  <p>Hello</p>  </div>
    输出
    safe to minify
  2. 2. Minify the HTML

    Remove comments, collapse whitespace between tags, and remove optional closing tags and quotes around attribute values where safe. Preserve whitespace inside <pre>, <textarea>, and <script> content. The result is a single compact line.

    入力
    <div>\n  <p>Hello</p>\n</div>
    输出
    <div><p>Hello</p></div>
  3. 3. Verify the page renders identically

    Open the minified HTML in a browser and compare with the original. Check that inline elements still have correct spacing and that <pre> content is preserved. Automated visual regression testing can catch issues.

    入力
    minified HTML
    输出
    renders identically

期待される結果

元のファイルと同じように描画される、より小さい HTML ファイル。

よくあるエラー

Inline elements lose spacing
Whitespace between inline elements (like <span>) can be significant. Use a minifier that collapses whitespace only between block-level elements, or preserve inline whitespace.
Script or style content is corrupted
Content inside <script> and <style> tags must not be whitespace-collapsed. Use a minifier that treats these as raw text.

トラブルシューティング指引

  • If the page looks different after minification, check <pre> and inline element whitespace.
  • Conditional comments (<!--[if IE]>) should be preserved for legacy IE support.

セキュリティ上の制限

  • Minification does not sanitize HTML. If the source has XSS vectors, they remain after minification.

関連ツール

参考链接