开发者

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

开发者 https://www.devze.com 2023-02-18 03:51 出处:网络
Closed. This question needs to be more focused. It is not currently accepting answers. Want to improve this question? Update the question so it focuses on one problem only by editing this
Closed. This question needs to be more focused. It is not currently accepting answers.

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 7 years ago.

Improve this question

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


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?


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.


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.


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.


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

  • js-minify filter https://developers.google.com/speed/pagespeed/module/filter-js-minify
  • css-rewrite filter https://developers.google.com/speed/pagespeed/module/filter-css-rewrite


You need to system(); this

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

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


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.


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 ??? ;)

0

精彩评论

暂无评论...
验证码 换一张
取 消