Minimize CSS in the header (compatible with @auto.)

My solution to minimize the css directly in the in the header:

<style>
<?php ob_start('minify');
function minify($buffer) {
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);    		
$buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);
$buffer = str_replace(array(' } ',' }','} ',';}'), '}', $buffer);
$buffer = str_replace(array(' { ',' {','{ '), '{', $buffer);
$buffer = str_replace(array(' : ',' :',': '), ':', $buffer);
return $buffer; }
include('assets/css/main.css');
if($page->template() != 'default'){
	include('assets/css/templates/' . $page->template() . '.css');
}
ob_end_flush(); ?>
</style>

Gist / Github: https://gist.github.com/starckio/ac1da52b9512122b05933a551efef21c

Thanks for sharing!

But why are you using an output buffer? Couldn’t you use file_get_contents() instead?

Also a quick note: This only really makes sense if you use Kirby’s caching. If you don’t, the (of course quite small) time it takes to minify the code is probably greater than the time saved (especially with gzip enabled).
Especially with large CSS files you also need to keep in mind that having the file as a separate asset is better for browser caching.

I’m not a developer, I’ve just adapted an old code to work with Kirby.
It may be a bad idea (I do not know) but I wanted to share. :slight_smile:

As I said, thanks for sharing! There will definitely be situations in which your code is useful. :slight_smile: