-
-
Save niladam/eef261ce19dfe0d84f476012c1bbe2d1 to your computer and use it in GitHub Desktop.
On-the-fly CSS Compression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* On-the-fly CSS Compression | |
* Copyright (c) 2009 and onwards, Manas Tungare. | |
* Creative Commons Attribution, Share-Alike. | |
* | |
* In order to minimize the number and size of HTTP requests for CSS content, | |
* this script combines multiple CSS files into a single file and compresses | |
* it on-the-fly. | |
* | |
* To use this in your HTML, link to it in the usual way: | |
* <link rel="stylesheet" type="text/css" media="screen, print, projection" href="/css/compressed.css.php" /> | |
*/ | |
$files = array( | |
"base.core.css", | |
"base.layout.css", | |
"base.menu.css" | |
); | |
/** | |
* Ideally, you wouldn't need to change any code beyond this point. | |
*/ | |
$buffer = ''; | |
foreach ( $files as $file ) | |
$buffer .= @file_get_contents( $file ); | |
// Remove comments | |
$buffer = preg_replace( '!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer ); | |
// Remove space after colons | |
$buffer = str_replace(': ', ':', $buffer); | |
// Remove whitespace | |
$buffer = str_replace( array( "\r\n", "\r", "\n", "\t" ), '', $buffer ); | |
// Collapse adjacent spaces into a single space | |
//$buffer = ereg_replace(" {2,}", ' ',$buffer); | |
// Remove spaces that might still be left where we know they aren't needed | |
$buffer = preg_replace( "/\s*([\{\}>~:;,])\s*/", "$1", $buffer ); | |
// Remove last semi-colon in a block | |
$buffer = preg_replace( "/;\}/", "}", $buffer ); | |
// Shorten HEX Color Codes (#666666 to #666) | |
$buffer = preg_replace( "/#([0-9a-fA-F])\\1([0-9a-fA-F])\\2([0-9a-fA-F])\\3/", "#$1$2$3", $buffer ); | |
// Enable GZip encoding. | |
ob_start( "ob_gzhandler" ); | |
// Enable caching | |
header( 'Cache-Control: public' ); | |
// Expire in 7 days | |
header( 'Expires: ' . gmdate('D, d M Y H:i:s', time() + 604800) . ' GMT' ); | |
// Set the correct MIME type, because Apache won't set it for us | |
header( 'Content-type: text/css' ); | |
// Write everything out | |
echo( $buffer ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment