PHP小技巧之JS和CSS優(yōu)化工具Minify的使用方法
一、實現(xiàn)合并和壓縮多個JS和CSS文件的代碼
HTML:
<link rel="stylesheet" type="text/css" href="cssmin.php?get=base,style1,style2,global&path=css/&v=20131023" />
<script type="text/javascript" src="jsmin.php?get=jquery-1.6.4.min.js,minjquery.js,minjquery.ui.js,test.js,global.js&path=js/&v=20131023"></script>
PHP:
//輸出JS
header ("Content-type:Application/x-javascript; Charset: utf-8");
if(isset($_GET)) {
$files = explode(",", $_GET['get']);
$str = '';
foreach ($files as $key => $val){
$str .= file_get_contents($_GET['path'].$val);
}
$str = str_replace("\t", "", $str); //清除空格
$str = str_replace("\r\n", "", $str);
$str = str_replace("\n", "", $str);
// 刪除單行注釋
$str = preg_replace("/\/\/\s*[a-zA-Z0-9_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/", "", $str);
// 刪除多行注釋
$str = preg_replace("/\/\*[^\/]*\*\//s", "", $str);
echo $str;
}
//輸出CSS
header ("content-type:text/css; charset: utf-8");
if(isset($_GET)) {
$files = explode(",", $_GET['get']);
$fc = '';
foreach ($files as $key => $val){
$fc .= file_get_contents($_GET['path'].$val.".css");
}
$fc = str_replace("\t", "", $fc); //清除空格
$fc = str_replace("\r\n", "", $fc);
$fc = str_replace("\n", "", $fc);
$fc = preg_replace("/\/\*[^\/]*\*\//s", "", $fc);
echo $fc;
}
只是個簡單原型,沒有封裝。另外,合并后的文件記得配合緩存
二、Minify的使用方法
1、從code.google.com/p/minify/下載最新版Minify并解壓縮,將"min"文件夾連同里面的內(nèi)容一起復制到DOCUMENT_ROOT目錄下(即網(wǎng)站跟目錄)。
可以修改文件夾名"min"
2、在"min/groupsConfig.php"里配置g參數(shù)
return array(
// 'js' => array('//js/file1.js', '//js/file2.js'),
// 'css' => array('//css/file1.css', '//css/file2.css'),
);
3、在網(wǎng)頁中按照如下方式引用就可以了:
<script type="text/javascript" src="/min/g=js&20140519"></script>
后面的數(shù)字可以用更新日期來作標志,"min"和步驟1里的名稱對應。
4、性能優(yōu)化,請參考code.google.com/p/minify/wiki/CookBook
注意:
1、需要將httpd.conf里的rewrite_module模塊開啟
2、開發(fā)過程中,可以將調(diào)試模式開啟,開發(fā)完畢后再將調(diào)試模式關(guān)閉,可以利用火狐瀏覽器的firebug來查看
$min_allowDebugFlag = true
相關(guān)文章
PHP實現(xiàn)的62進制轉(zhuǎn)10進制,10進制轉(zhuǎn)62進制函數(shù)示例
這篇文章主要介紹了PHP實現(xiàn)的62進制轉(zhuǎn)10進制,10進制轉(zhuǎn)62進制函數(shù),結(jié)合具體實例形式分析了php針對62進制與10進制相互轉(zhuǎn)換的操作技巧,需要的朋友可以參考下2019-06-06
php數(shù)組添加與刪除單元的常用函數(shù)實例分析
這篇文章主要介紹了php數(shù)組添加與刪除單元的常用函數(shù),實例分析了array_push、array_pop、array_shift及array_unshift等函數(shù)的使用技巧,需要的朋友可以參考下2015-02-02
PHP實現(xiàn)對文本數(shù)據(jù)庫的常用操作方法實例演示
這篇文章主要介紹了PHP實現(xiàn)對文本數(shù)據(jù)庫的常用操作方法,需要的朋友可以參考下2014-07-07
對象失去焦點時自己動提交數(shù)據(jù)的實現(xiàn)代碼
生產(chǎn)線上,提升輸入員輸入效率,在沒有購買到Bar code槍之前,需要修改程序,即是說當mouse光標離開TextBox之后,數(shù)據(jù)自動提交到數(shù)據(jù)庫中2012-11-11

