Javascript 如何即时缩小 JS 或 CSS
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5389822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to minify JS or CSS on the fly
提问by gourav
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.
如何在运行时/运行时缩小 JS 和 CSS,以便在运行时/运行时缩小原始代码结构,以便我可以将原始代码结构保留在我的服务器中。
回答by Krzysiu Jarzyna
After a lot of searching and sites optimizations i really recommend to use this script for CSS files:
经过大量搜索和网站优化后,我真的建议将此脚本用于 CSS 文件:
<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.
它将所有 css 文件压缩为一个并将其传递到 html 中,从而将额外请求的数量减少到零。如果您更喜欢将样式粘贴到 html 中,您也可以制作自己的compressed.css 文件。
回答by Andrew Wilkinson
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. PersonallyI prefer Fabric, but there are other tools are available.
我认为您的问题实际上应该是:如何可靠且可重复地更新我的实时服务器?您需要的是一个自动部署脚本。我个人更喜欢Fabric,但还有其他工具可用。
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.
自动部署脚本将允许您运行单个命令,该命令将转到实时服务器并更新源代码,运行任何部署步骤(例如缩小 javascript)并重新启动网络服务器。
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.
您真的不想即时缩小 javascript 或 css 文件,您应该在部署时执行一次,然后在您的代码中使用一个变量来指定这是否是实时部署。如果变量为真,那么你的文件链接应该是最小化版本的链接,如果它是假的,那么它们应该是正常版本的链接。
There are a number of programs which perform minimization, one that hasn't been mentioned yet is JSMin.
有许多程序可以执行最小化,其中一个尚未提及的是JSMin。
回答by KIKO Software
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.
如果您的目标是使 JavaScript 的可读性稍差,并在运行时执行此操作,则可以保持非常、非常、简单。只需三行代码,您就可以在几毫秒内实现完全缩小。
// 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?
这不会进行任何语法检查。使用此代码后,代码可能会失效。检查你的 JS 中的行尾,是一个 ';' 失踪的地方?
回答by Steven Ryssaert
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.
缩小 JS/CSS 文件的目标是更快地解析(并且占用更少的磁盘空间)。通过在运行时缩小它,这种好处将完全丧失。
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.
编辑:@Ant 的帖子为我澄清了这一点。
回答by Mathias Bynens
HTML5 Boilerplatecomes with a handy build script that compresses JS, CSS, images and much more. Check it out!
HTML5 Boilerplate带有一个方便的构建脚本,可以压缩 JS、CSS、图像等等。一探究竟!
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.
正如其他答案中所解释的那样,“真正的”即时缩小(每次请求时动态压缩文件)并不是一个好主意。
回答by Stefan Gehrig
Asseticis a nice project that helps in organizing resources such as CSS and Javascript including minification. See herefor an introduction.
Assetic是一个不错的项目,它有助于组织资源,例如 CSS 和 Javascript,包括缩小。请参阅此处的介绍。
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.
通常,运行时压缩应始终与服务器端的可靠缓存以及客户端和代理缓存的使用结合到浏览器。
回答by stefano di luca
If you have full control of your Apache / Ngnix configuration, a great option (in general) would be to enable the PageSpeedmodule, in your case with
如果您可以完全控制您的 Apache / Ngnix 配置,一个很好的选择(通常)是启用PageSpeed模块,在您的情况下
- 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
回答by dynamic
You need to system();
this
你需要system();
这个
$ java -jar yuicompressor-x.y.z.jar
$ java -jar yuicompressor-xyzjar
回答by Rajendra
Thats is exactly what WebUtilities(for J2EE) does. Here is the link.
这正是WebUtilities(对于 J2EE)所做的。链接在这里。
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
- 在一个请求中提供多个 JS 或 CSS 文件
- 为浏览器缓存的 JS、CSS 和图像文件添加 Expires 标头
- 即时缩小 JS、CSS 文件
- 缩小内联 CSS 和 JS 代码块
- 将字符编码添加到您的响应中
- 服务器压缩内容(gzip/compress/deflate)
- 通过避免重新处理来缓存响应以加快加载速度
Please have a look in case you find it interesting.
如果您觉得有趣,请看一看。
回答by Alice Wonder
I am doubtful that this minification craze really makes that big of a difference if the JS is sent with zlib compression.
如果 JS 是使用 zlib 压缩发送的,我怀疑这种压缩热潮是否真的会产生如此大的不同。
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).
首先,空白压缩得非常好,因此缩小导致的文件大小减少可能只是大型库(例如 jQuery)的主要问题(除非您需要黑客版本,否则应该从 CDN 提供服务)。
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.
Seconfly,JS 通常由客户端缓存,因此除非您在不同页面上使用许多不同的脚本,否则大多数页面加载不会产生任何影响。
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.
缩小的问题以及我为什么不这样做(除了像 jQuery 这样的东西): A)它去掉了注释,所以除非你重新添加它们,否则像版权声明这样的东西会丢失。这可能会导致违反许可证,因为即使是许多 OSS 许可证也要求版权完整。
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.
B) 当出现问题时,很高兴看到服务器正在服务的实际代码,以防它碰巧与您的工作副本不同。压缩代码在这方面做得不好。
My personal opinion - zlib compress on the fly, yes. minify - only for really large files.
我的个人意见 - zlib 即时压缩,是的。缩小 - 仅适用于非常大的文件。
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 ??? ;)
将 JS 解析为解释器的性能 - 也许如果浏览器在具有 32MB RAM 的 Apple Performa 上运行。我不认为它对大多数脚本产生了现实世界的影响。速度慢的页面通常很慢,因为同时运行的代码效率低下,或者向过载的服务器发出过多请求。(即,您真的需要在我输入每个字母时检查用户名的可用性吗?当我更改到不同的字段或单击提交时,您不能检查吗???;)