November 25, 2008 8

CSS deployment – combine css files into a master file

By admin in css

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

8 Responses to “CSS deployment – combine css files into a master file”

  1. [...] Minimize HTTP requests by merging all CSS files into one single file. [...]

  2. A simpler way using PHP’s glob

    header('Content-type: text/css');
     
    $path_to_css = 'assets/css/';
     
    if($files = glob($path_to_css .'*.css')) {
    	foreach($files as $file) {
    		include_once($file);
    	}
    }
  3. Good For Yslow Performance :) checker

  4. Jon Raasch says:

    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);
    ?>

  5. Ideally, expiration and gzipping rules should be enabled on the Web-server level (Apache virtualhost configuration) and not in a PHP code.

  6. Dave Allen says:

    I’m pretty new to all this, but with a simple adjustment you could do the same with all the JavaScript too.

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

  8. kitt says:

    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.

Leave a Reply

Comment Spam Protection by WP-SpamFree