Saturday, April 20, 2013

How to Compress CSS and Javascript files

1.Create minify.php, paste this below code and save.
<?php
header('Content-type: text/css');
ob_start("compress");
function compress($buffer) {

  $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
  /* remove tabs, spaces, newlines, etc. */
  $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);
  return $buffer;
}
/* your css files : add one by one */
include("stylesheet.css");
include("common.js");
ob_end_flush();
?>


2. In index.php or header file inclusions call the minify.php like below


<!doctype html>
<html>
<head>
<link rel="stylesheet" href="minify.php" type="text/css" media="all" />
</head>
<body>
<div>Hello</div>
</body>
</html>