How to minify JS or CSS on the fly [closed] How to minify JS or CSS on the fly [closed] php php

How to minify JS or CSS on the fly [closed]


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.


I think your question should actually be: How can I reliably and repeatably update my live servers? What you need is an automatic deployment script. Personally I prefer Fabric, but there are other tools are available.

An automatic deployment script will allow you to run a single command which will go to live servers and update the source code, run any deployment steps (such as minifying javascript) and restart the webserver.

You really don't want to be minifying javascript or css files on the fly, you should do that once at deployment and then have a variable in your code that specifies whether this is a live deployment or not. If the variable is true then your links to the files should be links to the minimized version, if it's false then they should be to the normal versions.

There are a number of programs which perform minimization, one that hasn't been mentioned yet is JSMin.


If your goal is to make your JavaScript slightly less readable, and do this at runtime, you could keep it very, very, simple. With just three lines of code you can get a long way toward total minification within a few milliseconds.

// make it into one long line$code = str_replace(array("\n","\r"),'',$code);// replace all multiple spaces by one space$code = preg_replace('!\s+!',' ',$code);// replace some unneeded spaces, modify as needed$code = str_replace(array(' {',' }','{ ','; '),array('{','}','{',';'),$code);

This does not do any syntax checking whatsoever. Code can become invalid after using this. Check the end of the lines in your JS, is a ';' missing somewhere?