47

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.

Bud Damyanov
  • 30,171
  • 6
  • 44
  • 52
gourav
  • 1,397
  • 5
  • 20
  • 31
  • 19
    Why don't you keep the two versions? And use Minified in production and full in development? – Michael Laffargue Mar 22 '11 at 10:31
  • 5
    +1 Louskan, best practice is to keep two versions. – Fareesh Vijayarangam Mar 22 '11 at 10:33
  • 1
    It can sometimes make sense to want a way to minify on the fly. For example I'm looking for code that I can insert into my existing cache system, so I just need a simple script to minify a string of CSS/JS, and my own code will take care of the caching. – orrd Sep 17 '15 at 17:24

10 Answers10

24

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.

Angel Politis
  • 10,955
  • 14
  • 48
  • 66
Krzysiu Jarzyna
  • 391
  • 2
  • 8
  • its great if you could add how to save to compressed.css and load that! if i have do it i will update – Develop4Life Jun 29 '15 at 07:53
  • 4
    While pasting the CSS into the HTML indeed reduces the amount of requests (with 1), it also prevents the CSS from being cached. A good caching meganism reduces both the number of requests and the size of the HTML documents. – DavidKunz Sep 22 '16 at 12:37
  • Which is why you should always measure what's changing. If you're inlining your critical path css good chance you'll see a reduction in perceived latency, even though it's not cached, especially on mobile. – vhs Apr 18 '17 at 21:41
  • You can save minified CSS in localstorage as a cache literal, then use AJAX/Fetch HEAD request to check if the CSS file has been updated. If not, do not download the file and just load the CSS from the Storage. – KHAYRI R.R. WOULFE Jun 02 '22 at 03:57
  • This may cause render blocking. You should only provide main css in styles and other in link tag that should be loaded async after document render. – Amir Fo Feb 17 '23 at 09:16
9

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.

Andrew Wilkinson
  • 10,682
  • 3
  • 35
  • 38
8

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?

KIKO Software
  • 15,283
  • 3
  • 18
  • 33
  • 1
    I've just tested this version and it generates JS error if there's a simple comment (//) in the original JS. As no line breaks here, check my comment for visualization at http://imgur.com/a/TzM30 – err Jul 29 '17 at 14:19
4

HTML5 Boilerplate comes with a handy build script that compresses JS, CSS, images and much more. Check it out!

As explained in the other answers, “real” on-the-fly minification (dynamically compress a file every time it’s requested) wouldn’t be a very good idea.

Mathias Bynens
  • 144,855
  • 52
  • 216
  • 248
  • 14
    When minified on the fly, just cache it in the file. If any source file timestamp changes - minify and cache it again on the fly. Worked for years in all my projects. – Meglio Mar 18 '13 at 15:53
3

If I may speak so freely;

Minifying a JS/CSS file would have as goal that it parses more quickly ( and also use up less disk space). By minifying it at runtime, that benefit would be completely lost.

Perhaps I am mistaken in your final goal, but this is what comes to my mind at first.

Edit: post by @Ant clarified it for me.

Steven Ryssaert
  • 1,989
  • 15
  • 25
  • 3
    The runtime minified file is cached, obviously. Even then, in good systems, it's minified at website start. When you have 258 properly refactored and architected JS files for your extremely larger Angular application, this is required. It must be runtime for debugging. Debug=true (depending on your system), might show you the true files and allow stepping. – David Betz May 01 '15 at 20:57
  • This is not an answer. Place your comments in the question itself – Aurovrata Oct 03 '21 at 05:59
2

If you have full control of your Apache / Ngnix configuration, a great option (in general) would be to enable the PageSpeed module, in your case with

stefano di luca
  • 147
  • 1
  • 10
  • I tried pagespeed and it sometimes compresses, sometimes not, others give a 404... I gave up with this solution – marcostvz May 31 '16 at 12:29
2

Assetic is a nice project that helps in organizing resources such as CSS and Javascript including minification. See here for an introduction.

Generally runtime minification should always be combined with solid caching on the server side and the usage of client and proxy caches along the way to the browser.

Stefan Gehrig
  • 82,642
  • 24
  • 155
  • 189
0

You need to system(); this

$ java -jar yuicompressor-x.y.z.jar

http://developer.yahoo.com/yui/compressor/

dynamic
  • 46,985
  • 55
  • 154
  • 231
-1

Thats is exactly what WebUtilities (for J2EE) does. Here is the link.

http://code.google.com/p/webutilities/

It does the minification and merging on the fly. It also has caching to avoid reruning the minification or reprocessing of a resource if resource not modified. It also helps with following optimizations.

  • Serve multiple JS or CSS files in one request
  • Add Expires header for JS, CSS and Image files to be cached by browser
  • Minify JS, CSS files on the fly
  • Minify Inline CSS and JS code blocks
  • Add Character Encoding to your response
  • Server compressed contents (gzip/compress/deflate)
  • Cache responses to speed loading by avoiding reprocessing

Please have a look in case you find it interesting.

Rajendra
  • 29
  • 1
-2

I am doubtful that this minification craze really makes that big of a difference if the JS is sent with zlib compression.

First, white space compresses extremely well, so the reduced filesize that results from minification is probably only a major issue with large libraries such as jQuery (which probably should be served from a CDN unless you need a hacked version).

Seconfly, JS is usually cached by the client so unless you use a lot of different scripts on different pages, most page loads it is not going to make a difference.

The problems with minification and why I do not do it (except with things like jQuery): A) It strips out comments, so unless you re-add them, things like copyright notices are lost. This could result in a license violation, since even many OSS licenses require the copyright be intact.

B) When there is a problem, it is nice to see the actual code the server is serving just in case it happens to be different than your working copy. Minified code does not do well in that respect.

My personal opinion - zlib compress on the fly, yes. minify - only for really large files.

Performance parsing the JS into the interpreter - maybe if the browser is running on an Apple Performa with 32MB of RAM. I do not buy that it makes a real world difference with most scripts. Pages that are slow are usually slow because of too much inefficient code running at same time or are making too many requests to overloaded servers. (IE do you really need to check availability of username as I type each letter? Can't you check when I change to a different field or when I click submit ??? ;)

Alice Wonder
  • 896
  • 2
  • 9
  • 17
  • A. - is not true. Usually you can configure minifier to keep copyright comments. For example, see uglify documentation. – Meglio Mar 18 '13 at 15:59
  • I disagree. When pages load they stop loading files if the file being loaded is a script (unless the async attribute is in use). If you open DevTools when a slow page is loading, you'll see that it is hanging because a script isn't being downloaded quickly. Cutting the script down to size helps somewhat. – Luke Madhanga Jul 06 '14 at 10:47
  • 1
    As people like to say, you were on the "wrong side of history". Minification (a runtime process-- with the ability to enter "debug" modehas proven to be required for even the most small applications. With most AngularJS applications having dozens or hundreds of JS files, you have to combine/minify. This debate has been over for years. You should update your rant to reflect this. – David Betz May 01 '15 at 20:54
  • 1
    Wow the date on my post is 2011. I do minify now, I keep them un-minified on the server but minify on the fly when served. It is sometimes funny to look back at old opinions on a topic. – Alice Wonder May 18 '15 at 22:03
  • 2
    @AliceWonder don't you wish you could go back 4 years in time and punch your younger self in the face? `:D` *(PS: just kidding)* – ADTC Dec 20 '15 at 13:32