一、实现合并和压缩多个JS和CSS文件的代码
HTML:
PHP:
$str = str_replace("\t","",$str); //清除空格@H_502_9@$str = str_replace("\r\n",$str); @H_502_9@$str = str_replace("\n",$str);
// 删除单行注释@H_502_9@$str = preg_replace("/\/\/\s*[a-zA-Z0-9_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/",$str); @H_502_9@// 删除多行注释@H_502_9@$str = preg_replace("/\/\*[^\/]*\*\//s",$str);
echo $str;@H_502_9@}
//输出CSS@H_502_9@header ("content-type:text/css; charset: utf-8");@H_502_9@if(isset($_GET)) {@H_502_9@$files = explode(",$_GET['get']);@H_502_9@$fc = '';@H_502_9@foreach ($files as $key => $val){@H_502_9@$fc .= file_get_contents($_GET['path'].$val.".css");@H_502_9@} @H_502_9@$fc = str_replace("\t",$fc); //清除空格@H_502_9@$fc = str_replace("\r\n",$fc); @H_502_9@$fc = str_replace("\n",$fc); @H_502_9@$fc = preg_replace("/\/\*[^\/]*\*\//s",$fc); @H_502_9@echo $fc; @H_502_9@}@H_502_9@
只是个简单原型,没有封装。另外,合并后的文件记得配合缓存
二、Minify的使用方法
1、从code.google.com/p/minify/下载最新版Minify并解压缩,将"min"文件夹连同里面的内容一起复制到DOCUMENT_ROOT目录下(即网站跟目录)。
2、在"min/groupsConfig.PHP"里配置g参数
3、在网页中按照如下方式引用就可以了:
后面的数字可以用更新日期来作标志,"min"和步骤1里的名称对应。
4、性能优化,请参考code.google.com/p/minify/wiki/CookBook
注意:
1、需要将httpd.conf里的rewrite_module模块开启
2、开发过程中,可以将调试模式开启,开发完毕后再将调试模式关闭,可以利用火狐浏览器的firebug来查看