HTML¶
minify_html makes a web page smaller. It removes what a browser ignores,
such as comments and extra spaces, so the page loads faster and looks the
same. See Minifier if the word is new to you.
A small call is enough:
import korpress
korpress.minify_html('<p> Hello, <b>world</b> </p><!-- bye -->')
# '<p>Hello, <b>world</b></p>'
The spaces at the ends of the paragraph and the repeated spaces are gone,
the comment is gone, and the space before <b> stays because a browser
shows it.
Before and after¶
import korpress
src = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> My page </title>
<style>
body { margin : 0px }
</style>
</head>
<body>
<!-- main content -->
<h1 class="title">Hello, <b>world</b> !</h1>
<p>
Some text with a <a href="/docs" class="link big">link</a>.
</p>
<input type="checkbox" checked="checked" disabled="">
<script>
var a = 1 ;
// log it
console.log( a ) ;
</script>
</body>
</html>
"""
print(korpress.minify_html(src))
The output is one line (cut here to fit):
<!DOCTYPE html><html lang=en><head><meta charset=utf-8><title>My page</title><style>body{margin:0}</style></head><body><h1 class=title>Hello, <b>world</b> !</h1><p>Some text with a <a href=/docs class="link big">link</a>.</p><input type=checkbox checked disabled><script>var a=1;console.log(a)</script></body></html>
Look at three details. The comment is gone. <b>world</b> ! keeps its
space, because a browser shows it. class="link big" keeps its quotes,
because the value has a space.
The idea¶
minify_html removes what a browser ignores: comments, extra spaces, line
breaks between blocks, quotes around simple attribute values. It handles the
code inside the page too. A <style> block, a style="" attribute and a
<script> block go through the CSS and JavaScript
minifiers (see Inline script and style).
The hard part of HTML is white space. Some spaces are shown on screen and
some are not. korpress follows what a browser does: a space between two
blocks (<p> and <p>) is not shown, so it goes. A space between two inline
tags (<b> and <i>) is shown, so one space stays.
korpress does not guess what you meant. It never adds, moves or removes tags.
What korpress changes¶
Each row is a real input and the output you get.
| Rule | Before | After |
|---|---|---|
| Drop white space between blocks | <div>\n <p>a</p>\n <p>b</p>\n</div> |
<div><p>a</p><p>b</p></div> |
| Drop white space in lists | <ul>\n<li>a</li>\n<li>b</li>\n</ul> |
<ul><li>a</li><li>b</li></ul> |
| Trim the ends of a block | <p> a </p> |
<p>a</p> |
| Collapse a run of spaces to one | <p>Hello <b>big</b> <i>world</i> !</p> |
<p>Hello <b>big</b> <i>world</i> !</p> |
| A tab or line break in text becomes a space | <p>a\tb</p> |
<p>a b</p> |
No space around <br> |
<p>a <br> b</p> |
<p>a<br>b</p> |
| Remove comments | <p>a<!-- c -->b</p> |
<p>ab</p> |
| Remove quotes that are not needed | <a href="/x">x</a> |
<a href=/x>x</a> |
| Tighten spaces in a tag | <a href = "/x" class=" a b " >x</a> |
<a href=/x class="a b">x</a> |
| Boolean attributes | <input disabled="" checked="checked"> |
<input disabled checked> |
Remove an empty class or style |
<p class="" id="a">x</p> |
<p id=a>x</p> |
| Trim the value of a link | <a href=" x ">y</a> |
<a href=x>y</a> |
| Void tags lose the slash | <br/><hr /> |
<br><hr> |
Remove default type values |
<script type="text/javascript">var a = 1 ;</script> |
<script>var a=1</script> |
Remove type="text/css" |
<link rel=stylesheet type="text/css" href=a.css> |
<link rel=stylesheet href=a.css> |
Minify <style> |
<style>\n a { color : red }\n</style> |
<style>a{color:red}</style> |
Minify <script> |
<script>\n var a = 1 ;\n // x\n</script> |
<script>var a=1</script> |
| Minify a module | <script type="module">import a from "b" ;</script> |
<script type=module>import a from"b"</script> |
Minify style="" |
<p style=" color : red ; margin : 0px ">x</p> |
<p style=color:red;margin:0>x</p> |
| Minify JSON scripts | <script type="application/ld+json">{ "a" : [ 1 , 2 ] }</script> |
<script type=application/ld+json>{"a":[1,2]}</script> |
A few details:
- A value keeps its quotes when it holds a space, a quote,
=,<,>or a backtick. When it holds a double quote, korpress uses single quotes (title='a "b"'). - Only these attributes are shortened to their bare name:
allowfullscreen,async,autofocus,autoplay,checked,controls,default,defer,disabled,formnovalidate,hidden,inert,ismap,itemscope,loop,multiple,muted,nomodule,novalidate,open,playsinline,readonly,required,reversedandselected. And only when the value is empty or the same as the name.hidden="until-found"stayshidden=until-found. - Only
classhas its inner spaces collapsed. These attributes are trimmed:href,src,action,poster,cite,dataandformaction. - The inline JavaScript keeps its
/*! ... */license comments, likeminify_jsdoes, and loses the;at the very end. - JSON scripts are
application/json,application/ld+json,importmapandspeculationrules. Only the space outside strings goes. A JSON string such as"x y"keeps its two spaces.
Options¶
korpress.minify_html(
src,
*,
collapse_whitespace=True,
remove_comments=True,
minify_css=True,
minify_js=True,
)
All four are keyword-only and must be a bool.
collapse_whitespace¶
False leaves the white space in text as it is. Attributes and tags are
still tightened, and comments are still removed.
src = "<p> a </p>\n<p>b</p>"
korpress.minify_html(src)
# '<p>a</p><p>b</p>'
korpress.minify_html(src, collapse_whitespace=False)
# '<p> a </p>\n<p>b</p>'
korpress.minify_html("<p class=a> hi </p>", collapse_whitespace=False)
# '<p class=a> hi </p>'
remove_comments¶
False keeps <!-- ... --> comments. Conditional comments
(<!--[if IE]>...<![endif]-->) are always kept, whatever you pass.
src = "<p>a<!-- c --> b</p>"
korpress.minify_html(src)
# '<p>a b</p>'
korpress.minify_html(src, remove_comments=False)
# '<p>a<!-- c --> b</p>'
minify_css and minify_js¶
They switch off the inline minifiers. minify_css=False covers <style>
blocks and style="" attributes. minify_js=False covers <script>
blocks. Everything else is still minified.
src = (
"<style> a { color : red } </style>"
"<script> var a = 1 ; </script>"
"<p style=' margin : 0px '>x</p>"
)
korpress.minify_html(src)
# '<style>a{color:red}</style><script>var a=1</script><p style=margin:0>x</p>'
korpress.minify_html(src, minify_css=False)
# '<style> a { color : red } </style><script>var a=1</script><p style=" margin : 0px ">x</p>'
korpress.minify_html(src, minify_js=False)
# '<style>a{color:red}</style><script> var a = 1 ; </script><p style=margin:0>x</p>'
korpress.minify_html(src, minify_css=False, minify_js=False)
# '<style> a { color : red } </style><script> var a = 1 ; </script><p style=" margin : 0px ">x</p>'
On the command line, --no-css, --no-js and --keep-comments do the same
as minify_css=False, minify_js=False and remove_comments=False. There is
no flag for collapse_whitespace. See Command line.
In depth¶
This part is for exact behavior, edge cases and limits.
korpress does not build a tree of the page. It reads the page once, from start to end.
What it never changes¶
Each claim below was run, and the output is shown.
| Left alone | Before | After |
|---|---|---|
Text in <pre> |
<pre>\n a b\n</pre> |
<pre>\n a b\n</pre> |
Tags inside <pre> |
<pre><code> x\n y</code></pre> |
<pre><code> x\n y</code></pre> |
Text in <textarea> |
<textarea>\n a b\n</textarea> |
<textarea>\n a b\n</textarea> |
| The space between two inline tags | <a>a</a> <a>b</a> |
<a>a</a> <a>b</a> |
| The spaces inside an inline tag | <p>a<b> b </b>c</p> |
<p>a<b> b </b>c</p> |
| The space between two buttons | <button> Save </button> <button> Cancel </button> |
<button> Save </button> <button> Cancel </button> |
| Text in svg | <svg viewBox="0 0 1 1">\n <path d="M0 0"/>\n <text> a b </text>\n</svg> |
<svg viewBox="0 0 1 1"><path d="M0 0"/><text> a b </text></svg> |
<style> in svg |
<svg><style> a { b : c } </style></svg> |
<svg><style> a { b : c } </style></svg> |
| A value that is not a class or a link | <input value=" a b "> |
<input value=" a b "> |
| A title | <a title=" a b ">x</a> |
<a title=" a b ">x</a> |
An empty value that is not class or style |
<img src=a.png alt=""> |
<img src=a.png alt=""> |
| An event handler | <p onclick="go( 1 )">x</p> |
<p onclick="go( 1 )">x</p> |
| Entities | <a href="x=1&y=2">x</a> |
<a href="x=1&y=2">x</a> |
| A non-breaking space | <p>a b</p> |
<p>a b</p> |
| A script of another type | <script type="text/template"> <b> {{x}} </b> </script> |
<script type=text/template> <b> {{x}} </b> </script> |
| A script that cannot be minified | <script>var a = 'oops</script> |
<script>var a = 'oops</script> |
| A conditional comment | <!--[if IE]><p>ie</p><![endif]--><p>a</p> |
<!--[if IE]><p>ie</p><![endif]--><p>a</p> |
| The case of tags and attributes | <DIV ID="A">x</DIV> |
<DIV ID=A>x</DIV> |
A lone < or > in text |
<p>1 < 2 and 3 > 2</p> |
<p>1 < 2 and 3 > 2</p> |
| CDATA | <p>a</p><![CDATA[ x ]]><p>b</p> |
<p>a</p><![CDATA[ x ]]><p>b</p> |
(In the row, stands for the real character U+00A0. korpress
only collapses ASCII white space: space, tab, line feed, carriage return and
form feed.)
Why each one is safe:
<pre>and<textarea>show their text as you typed it. So their content, and the tags inside<pre>, are copied byte for byte.- Inline white space is shown by a browser.
<b>big</b> <i>world</i>shows a space, so a single space stays. That is the only safe choice: korpress cannot know that you did not want it. - svg text is drawn, so the space inside
<text>is kept as one space. Inside<svg>and<math>, attributes always keep their quotes, a/>stays, and<style>and<script>are copied as they are. - Attribute values keep their meaning. Only
classis cleaned, because a class list ignores extra spaces, and only the ends of links are trimmed. Other values (value,title,alt,data-*, event handlers) are yours, so they are not touched. - Scripts you did not write in JavaScript or JSON, such as a
text/template, are copied as they are, because korpress cannot know their syntax.
One thing to watch: white-space: pre in CSS¶
korpress knows <pre> and <textarea>. It does not read your CSS, so it
cannot know that an element is shown with white-space: pre. Its spaces are
collapsed like any other:
korpress.minify_html('<p style="white-space:pre">a b</p>')
# '<p style=white-space:pre>a b</p>'
korpress.minify_html("<code>a b</code>")
# '<code>a b</code>'
If you rely on that, use <pre> for those elements, or minify that page with
collapse_whitespace=False.
XHTML¶
A document that starts with <?xml is treated as XHTML. korpress then keeps
the quotes on every attribute and keeps />, because XML needs them. It does
not shorten boolean attributes either:
korpress.minify_html('<?xml version="1.0"?><p><input disabled="disabled" /></p>')
# '<?xml version="1.0"?><p><input disabled="disabled"/></p>'
Errors¶
minify_html never raises KorpressError. If an inline script cannot be
minified (for example a string that is never closed), korpress leaves that
one script as you wrote it and goes on with the rest of the page:
korpress.minify_html("<script>var a = 'x\n</script><p> a </p>")
# "<script>var a = 'x\n</script><p>a</p>"
Broken HTML does not make it fail either. A tag that is never closed, a stray
< or a missing quote are handled as well as possible. Because of that,
minify_html is not an HTML checker: check your pages before you minify them
if you need to know that they are valid.
A wrong type raises TypeError, as for any Python function:
korpress.minify_html(b"<p>")
# TypeError: 'bytes' object is not an instance of 'str'
korpress.minify_html("<p>", minify_js=1)
# TypeError: 'int' object is not an instance of 'bool'
korpress.minify_html("<p>", foo=True)
# TypeError: minify_html() got an unexpected keyword argument 'foo'
Good to know¶
- Minifying the output again gives the same output.
- To minify a file, use
minify_fileor the command line. - See Limits and safety for what korpress does not do.