合并和缩小多个 CSS/JS 文件 [英] Combine and Minify Multiple CSS / JS Files
问题描述
我正在尝试通过合并和压缩 CSS 和 JS 文件来优化站点性能.我的问题更多地是关于如何实现这一目标的(具体)步骤,考虑到我面临的真实情况(不过在其他开发者中也应该是典型的).
I am trying to optimize a site performance by consolidating and compressing the CSS and JS files. My question is more about the (concrete) steps on how to achieve this, given a real situation I was facing (should be typical among other developers too, though).
我的页面引用了几个 CSS 和 JS 文件,如下所示:
My page references several CSS and JS files like the following:
<!--
It's easier to work on smaller files during development.
Hence, the multiple CSS and JS files.
-->
<link type="text/css" rel="stylesheet" href="/css/main.css" />
<link type="text/css" rel="stylesheet" href="/css/secondary-1.css" />
<link type="text/css" rel="stylesheet" href="/css/secondary-2.css" />
<script type="text/javascript" src="/scripts/js/main.js"></script>
<script type="text/javascript" src="/scripts/js/adapter/adapter.js"></script>
<script type="text/javascript" src="/scripts/js/adapter/title-adapter.js"></script>
对于生产版本,我想将 3 个 CSS 文件合并为一个并使用例如缩小它YUI 压缩器.但是,我需要更新需要这 3 个文件的所有页面以引用新缩小的 CSS.这似乎容易出错(例如,您要在许多文件中删除和添加一些行).还有其他风险较低的方法吗?JS 文件也有同样的问题.
For the production release, I'd like to combine the 3 CSS files into one and minify it using e.g. YUI Compressor. But then, I'd need to update all pages that needs these 3 files to reference to the newly-minified CSS. This seems error-prone (e.g. you're removing and adding some lines in many files). Any other less-risky approach? The same issue for the JS files.
推荐答案
我最终使用 CodeKit 来连接我的 CSS 和 JS 文件.我发现真正有用的功能是能够在文件保存时进行连接;因为它监控各自的 CSS/JS 资产.一旦我将它们正确组合,例如到1个CSS和1个JS文件,其他所有文件都可以参考这2个.
I ended up using CodeKit to concatenate my CSS and JS files. The feature that I find really useful is the ability to do the concatenation upon file save; because it monitors the respective CSS / JS assets. Once I got them properly combined e.g. to 1 CSS and 1 JS files, all other files simply can refer to these 2.
您甚至可以要求 CodeKit 进行动态缩小/压缩.
You can even ask CodeKit to do on-the-fly minification / compression.
免责声明:我与 CodeKit 没有任何关联.我在网上随机找到了它,它在我的开发过程中起到了很好的作用.自从我一年多前第一次使用它以来,它还带来了很好的更新.
Disclaimer: I am not affiliated in any way with CodeKit. I randomly found it on the web and it has served as a great tool in my development process. It also comes with good updates since I first used it more than a year ago.
这篇关于合并和缩小多个 CSS/JS 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!