What does the HTML Minifier & Code Compressor do?
The HTML Minifier & Code Compressor strips redundant whitespace, line breaks, indentations, and HTML comments from raw HTML source code. It reduces document size and calculates compression metrics (original byte size, minified size, and percentage savings) to optimize web page load performance.
Core Concepts
Understanding HTML minification mechanics:
- Comment Stripping: Removes standard HTML comments (
<!-- ... -->) while preserving conditional comments where needed. - Inter-Tag Whitespace Collapsing: Removes whitespace between adjacent tags (e.g.
> <becomes><) and collapses consecutive spaces into single spaces. - Empty Attribute Stripping: Optionally removes empty attribute declarations (such as
class="") to trim additional bytes. - Performance Metrics: Computes exact byte counts before and after compression to benchmark bandwidth savings.
How to use the tool?
- Paste HTML Markup: Paste your unminified HTML code or template into the input editor or click Load Sample.
- Configure Options: Toggle Remove HTML comments and Collapse inter-tag whitespace.
- Minify & Copy: Click Minify HTML Code, review the compression savings, and click Copy or Download to export the compressed markup.
Related Developer Utilities
If you work with HTML markup, code formatting, and web optimization, explore these complementary tools:
- HTML Formatter & Beautifier: Re-indent and beautify unformatted HTML documents.
- HTML Syntax Validator: Check HTML element nesting and detect unclosed tags.
- HTML Tag Stripper: Strip HTML tags and extract clean plain text.
- HTML to Markdown Converter: Convert HTML markup into clean GitHub Flavored Markdown.
REST API Integration
Blueutils provides a free REST API endpoint (POST https://blueutils.com/api/html/html-minifier) to programmatically compress HTML markup code by stripping comments, inter-tag whitespace, and unnecessary line breaks.
API Request Parameters
| Name | Type | Description | Example |
|---|---|---|---|
rawText |
String | Raw HTML markup payload to minify. | "<div>\n <h1>Title</h1>\n</div>" |
options.removeComments |
Boolean | Optional. Strip HTML comments. Default: true. |
true |
options.collapseWhitespace |
Boolean | Optional. Collapse inter-tag spaces. Default: true. |
true |
options.removeEmptyAttributes |
Boolean | Optional. Remove empty attributes like class="". Default: false. |
false |
API Request Payload Examples
cURL
curl -X POST https://blueutils.com/api/html/html-minifier \
-H "Content-Type: application/json" \
-d '{
"rawText": "<div>\n <!-- Comment -->\n <h1>Title</h1>\n</div>",
"options": { "removeComments": true, "collapseWhitespace": true }
}'Python
import requests
url = "https://blueutils.com/api/html/html-minifier"
payload = {
"rawText": "<div>\n <!-- Comment -->\n <h1>Title</h1>\n</div>",
"options": { "removeComments": True, "collapseWhitespace": True }
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers)
print(response.json())Java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Main {
public static void main(String[] args) throws Exception {
String jsonPayload = """
{
"rawText": "<div>\\n <!-- Comment -->\\n <h1>Title</h1>\\n</div>",
"options": { "removeComments": true, "collapseWhitespace": true }
}
""";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://blueutils.com/api/html/html-minifier"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}API Response Parameters
| Name | Type | Description | Example |
|---|---|---|---|
isValid |
Boolean | Indicates whether minification succeeded. | true |
originalSize |
Number | Raw input byte size. | 45 |
minifiedSize |
Number | Minified output byte size. | 24 |
bytesSaved |
Number | Total bytes saved by minification. | 21 |
compressionRatio |
String | Percentage bandwidth savings. | "46.67%" |
minifiedText |
String | Compressed HTML markup string. | "<div><h1>Title</h1></div>" |
API Response Payload Examples
Success Response (HTTP 200 OK)
{
"isValid": true,
"originalSize": 45,
"minifiedSize": 24,
"bytesSaved": 21,
"compressionRatio": "46.67%",
"removeComments": true,
"collapseWhitespace": true,
"minifiedText": "<div><h1>Title</h1></div>",
"output": "<div><h1>Title</h1></div>"
}Validation Failure Response (HTTP 400 Bad Request)
{
"isValid": false,
"error": "Invalid input: HTML payload to minify cannot be empty."
}Rate Limit Exceeded Response (HTTP 429 Too Many Requests)
{
"error": "API rate limit exceeded. Please wait or contact support@blueutils.com."
}Why use an API to minify HTML?
Integrating the HTML Minifier API into static site generators, email template builders, or AI agent tool calling provides key benefits:
- Rapid Script Validation: Compresses server-rendered templates, email payloads, and CMS pages before deployment to reduce cloud bandwidth costs.
- Optimized Token Efficiency for AI Agents: LLMs frequently inject superfluous indentation into generated HTML. Calling the API compacts output code deterministically without consuming token budget.
- Deterministic Accuracy Without Hallucinations: Ensures 100% regex-safe whitespace compression and accurate byte metric calculation.
Native Usage
How to minify HTML locally in terminal environments or scripts:
Windows (CMD / PowerShell)
# Minify HTML in PowerShell
(Get-Content -Path .\index.html -Raw) -replace '<!--[\s\S]*?-->', '' -replace '\s+', ' ' -replace '>\s+<', '><' | Set-Content min.htmlLinux / Unix (Bash)
# Minify HTML using tr and sed in Linux
tr -d '\n\r' < index.html | sed -E 's/>[[:space:]]+</></g' > min.htmlPython
Using Python re:
import re
html = "<div>\n <!-- Comment -->\n <h1>Title</h1>\n</div>"
minified = re.sub(r'<!--[\s\S]*?-->', '', html)
minified = re.sub(r'\s+', ' ', minified)
minified = re.sub(r'>\s+<', '><', minified).strip()
print(minified)Java
Using Java String.replaceAll:
import java.nio.file.*;
public class HtmlMinifierExample {
public static void main(String[] args) throws Exception {
String html = Files.readString(Paths.get("index.html"));
String minified = html
.replaceAll("<!--[\\s\\S]*?-->", "")
.replaceAll("\\s+", " ")
.replaceAll(">\\s+<", "><")
.trim();
Files.writeString(Paths.get("min.html"), minified);
System.out.println("Minified successfully.");
}
}