phpでCSSファイルを圧縮転送してサイトの表示を高速化させる方法が紹介されていたのでメモ
3 ways to compress CSS files using PHP
サイトのパフォーマンスを上げる、PHPでCSSファイルを圧縮転送する各種方法
以下引用です。
1. ob_start で gzhandler を使う方法
<?php if(extension_loaded('zlib')){ob_start('ob_gzhandler');} header("Content-type: text/css"); ?>
body{ background-color:#000000; }
<?php if(extension_loaded('zlib')){ob_end_flush();}?>
2. 1の方法に、Expiresヘッダーを追加してローカルにキャッシュさせる方法
<?php
ob_start ("ob_gzhandler");
header ("content-type: text/css; charset: UTF-8");
header ("cache-control: must-revalidate");
$offset = 60 * 60 * 24 * 30; // 30 日間
$expire = "expires: " . gmdate ("D, d M Y H:i:s", time() + $offset) . " GMT";
header ($expire);
$css = "body{ background-color:red }";
echo $css;
ob_end_flush();
?>
3. 複数のCSSファイルを1つにまとめて改行、スペースを取り除いて出力
<?php
header('Content-type: text/css');
ob_start("compress");
function compress($buffer) {
/* remove comments */
$buffer = preg_replace('!/*[^*]**+([^/][^*]**+)*/!', '', $buffer);
/* remove tabs, spaces, newlines, etc. */
$buffer = str_replace(array("rn", "r", "n", "t", ' ', ' ', ' '), '', $buffer);
return $buffer;
}
/* your css files */
include('master.css');
include('typography.css');
include('grid.css');
include('print.css');
include('handheld.css');
ob_end_flush();
?>