Inlining stylesheets in Middleman 4

If you want to squeeze out that last bit of performance on your site like me you might consider inlining your stylesheets into the HTML. This saves a roundtrip to the server and can increase render performance. Now this definitely doesn't make sense in all cases but for sites with tiny stylesheets like mine it's a nice win to speed up (first) render.

This site is generated with Middleman so I looked around for existing solutions to inline stylesheets in Middleman. I found some solutions but unfortunately they didn't work anymore since Middleman 4 doesn't include Sprockets.

So I decided to whip up a little script myself. It scans the Middleman build/ directory looking for HTML files. Each <link rel="stylesheet"> tag within those files is replaced with a <style> tag, containing the css code contained in the stylesheet. Presto 🙂.

It's not a Middleman extension so I just have my Rakefile run it after middleman build. Since it's not tied to Middleman you can use it with any static site generator, or HTML file for that matter.

The script is available here. Let me know if it's useful to you.