How to minify JS or CSS on the fly

gourav picture gourav · Mar 22, 2011 · Viewed 75.3k times · Source

How to minify JS and CSS on the fly / runtime, so that I can keep the original code structure in my servers if its minified on the runtime / fly.

Answer

Krzysiu Jarzyna picture Krzysiu Jarzyna · May 22, 2015

After a lot of searching and sites optimizations i really recommend to use this script for CSS files:

<style>
<?php
     $cssFiles = array(
      "style.css",
      "style2.css"
    );

    $buffer = "";
    foreach ($cssFiles as $cssFile) {
      $buffer .= file_get_contents($cssFile);
    }
    $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
    $buffer = str_replace(': ', ':', $buffer);
    $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);
    echo($buffer);
?>
</style>

It compress all css files into one and past it into html, reducing the number of additional requests to zero. You can also make your own compressed.css file if you prefer this than pasting styles into html.