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"文件夾連同里面的內容一起復制到DOCUMENT_ROOT目錄下(即網站跟目錄)。
可以修改文件夾名"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、在網頁中按照如下方式引用就可以了:
<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ā)過程中,可以將調試模式開啟,開發(fā)完畢后再將調試模式關閉,可以利用火狐瀏覽器的firebug來查看
$min_allowDebugFlag = true
相關文章
PHP Memcached + APC + 文件緩存封裝實現(xiàn)代碼
PHP Memcached + APC + 文件緩存封裝實現(xiàn)代碼,需要的朋友可以參考下。2010-03-03PHP has encountered an Access Violation 錯誤的解決方法
一般是因為eaccelerator的問題,windows下容易出現(xiàn)這個問題。2010-01-01php使用json_decode后數(shù)字對象轉換成了科學計數(shù)法的解決方法
這篇文章主要介紹了php使用json_decode后數(shù)字對象轉換成了科學計數(shù)法的解決方法,涉及php操作json格式數(shù)據(jù)與數(shù)值轉換相關技巧,需要的朋友可以參考下2017-02-02數(shù)據(jù)結構之利用PHP實現(xiàn)二分搜索樹
這篇文章主要給大家介紹了關于數(shù)據(jù)結構之利用PHP實現(xiàn)二分搜索樹的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-10-10