Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 954
gourav Avatar asked Mar 22 '11 10:03

gourav


People also ask

How do you minify CSS and JS files?

To minify CSS, try CSSNano and csso. To minify JavaScript, try UglifyJS. The Closure Compiler is also very effective. You can create a build process that uses these tools to minify and rename the development files and save them to a production directory.


2 Answers

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.

like image 181
Krzysiu Jarzyna Avatar answered Sep 23 '22 15:09

Krzysiu Jarzyna


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.

like image 32
Andrew Wilkinson Avatar answered Sep 22 '22 15:09

Andrew Wilkinson