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.
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.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With