HACKER Q&A
📣 hoosieree

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:

    
    ...
    

Hello

lorem ipsum

dolor sit amet

And transforms it into this:

    

Hello

lorem ipsum

dolor sit amet

However, it should not always inline the css styles, because sometimes that would cause the result to be larger than the original, like this:

    
    ...
    

Hello

lorem ipsum

dolor sit amet

Here,

is shorter than

, 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.


  👤 wruza Accepted Answer ✓
But that’s exactly what gzip does. You may think okay, it looks for repeated patterns, but then after a decompression the browser sees tons of excessive-looking styles, classes, etc. So what? They are just temporary strings pipelined from gunzip routine into a parser, which then caches similar patterns into same structures anyway. Doing it by hand would unlikely save any cpu time, memory, or network bandwidth, at all. A single word of lorem ipsum has more pixel edges to hint and antialias than there are bytes in your html+css.

If you’re looking for a wider task, e.g. unused css class elimination, then start with webpack and its plugins.


👤 EddieDante
I don't think this is worth doing for the following reasons:

1. 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.


👤 vivegi
For an average static website, we are likely to have the number of HTML pages much greater than the number of CSS files. So, it is far more likely to have a common set of styles coded in a separate CSS file be practically more efficient than inlining the styles.

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.