Ask HN: How to “compile” HTML+CSS for minimal page size?
From the perspective of static site generation, is there a tool to compile HTML+CSS in order to minimize download size?
I'm imagining something which takes the following HTML+CSS:
<style>
h1{color:red;}
h2{color:blue;}
.custom{display:none;}
.custom2{display:inline;}
</style>
...
<h2>Hello</h2>
<div class="custom">
<p>lorem ipsum</p>
<p>dolor sit amet</p>
</div>
And transforms it into this: <h2 style="color:blue">Hello</h2>
<div style="display:none">
<p>lorem ipsum</p>
<p>dolor sit amet</p>
</div>
However, it should not always inline the css styles, because sometimes that would cause the result to be larger than the original, like this: <style>
h1{color:red;}
h2{color:blue;}
.custom{display:none;}
.custom2{display:inline;background-color:yellow;}
</style>
...
<h2>Hello</h2>
<div class="custom2">
<p class="custom2">lorem ipsum</p>
<p class="custom2">dolor sit amet</p>
</div>
Here, <p class="custom2"> is shorter than <p style="display:inline;background-color:yellow;">, so it should remain unchanged.I'm not talking about tools like https://htmlcompressor.com/compressor/ which only remove whitespace, or gzip compression. What I want is something that understands the semantics of HTML+CSS and can intelligently inline iff that reduces the size of the resulting HTML file.
4 comments
[ 4.5 ms ] story [ 20.0 ms ] thread1. Your HTML is never the heaviest part of a webpage unless the page is pure HTML without JavaScript, images, audio, video, or embeds.
2. Minification, compilation, etc. tends to obfuscate your code. This makes it hard to read if a newbie to the web wants to use "view source" to see how you make your pages so they can learn from you.
If you’re looking for a wider task, e.g. unused css class elimination, then start with webpack and its plugins.
Add to this, the caching of the CSS file upon the first HTML file's use by the browser makes any css inlining in the HTML not worthwhile. The caching would save a lot more bandwidth each time the HTML files are accessed (by the same browser).
This combined with HTTP compression is far superior to any inlined HTML+CSS.