Handy PHP script which reads a directory with css files and combines them automatically into one master stylesheet. No matter how many files you add while developing, before launch you can use a build script that merges them all so you can save HTTP requests.
This is just the snippet who combines the files, if you want to (and you definitely should) compress your styles, strip out all of the comments and whitespace etc. please refer to my first article on css deployment with a php snippet which lets you compress css files on the fly.
header('Content-type: text/css'); $path_to_css = '../assets/css'; function get_files($dir = '.', $sort = 0) { $files = scandir($dir, $sort); $files = array_diff($files, array('.', '..')); return $files; } $files = get_files($path_to_css, 1); foreach($files as $file) { include_once($path_to_css.'/'.$file); }
Tags: best practices, deployment, snippet
[...] Minimize HTTP requests by merging all CSS files into one single file. [...]
A simpler way using PHP’s glob
Good For Yslow Performance
checker
This is one of my favorite techniques. I also like to gzip it:
<?php
ob_start (“ob_gzhandler”);
header(“Content-type: text/css; charset: UTF-8″);
header(“Cache-Control: must-revalidate”);
$offset = 60 * 60 ;
$ExpStr = “Expires: ” .
gmdate(“D, d M Y H:i:s”,
time() + $offset) . ” GMT”;
header($ExpStr);
?>
Ideally, expiration and gzipping rules should be enabled on the Web-server level (Apache virtualhost configuration) and not in a PHP code.
I’m pretty new to all this, but with a simple adjustment you could do the same with all the JavaScript too.
Yes… with a small effort you could add gzip and create a simple cache: Save the combined and gziped files, and add a simple verification, if any of the files inside the css folderis newer than the cache, run the code again, else serve the saved one.
My favorite example of it is a sciprt called combine check it out – http://rakaz.nl/code/combine
This works if you don’t use cascading styles, where styles in one file are overwritten by styles in another file, unless you cascade in alphabetized files. That is to say, if you have p defined in typography.css, but p.header defined in ie.css, the p.header values may be lost if typography.css is included after ie.css.
For production sites, generating a single file and caching it is better than the generating this file each time on the fly.