前端調用方式
<link rel="stylesheet" href="cssmin.php?get=base,style1,style2,global&path=css/&v=20131023" />
<script src="jsmin.php?get=jquery-1.6.4.min.js,minjquery.js,minjquery.ui.js,test.js,global.js&path=js/&v=20131023"></script>
JS 合並輸出 (jsmin.php)
header("Content-type: application/x-javascript; charset: utf-8");
if (isset($_GET['get'])) {
$files = explode(",", $_GET['get']);
$str = '';
foreach ($files as $val) {
$str .= file_get_contents($_GET['path'] . $val);
}
// 簡易壓縮
$str = str_replace(["\t", "\r\n", "\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 合並輸出 (cssmin.php)
header("Content-type: text/css; charset: utf-8");
if (isset($_GET['get'])) {
$files = explode(",", $_GET['get']);
$fc = '';
foreach ($files as $val) {
$fc .= file_get_contents($_GET['path'] . $val . ".css");
}
$fc = str_replace(["\t", "\r\n", "\n"], '', $fc);
$fc = preg_replace("/\\/\\*[^\\/]*\\*\\//s", "", $fc); // 刪除註釋
echo $fc;
}
生產環境優化建議
- 緩存機制:生成合並文件落盤,配合
v 參數版本號控制瀏覽器緩存更新。
- 專業壓縮工具:建議使用
MatthiasMullie/minify、JSMinPlus 等成熟庫,支持語法解析級壓縮,避免正則誤傷代碼。
- 安全過濾:嚴格驗證
path、get 參數,防止目錄遍歷讀取敏感文件。
- HTTP/2:若服務器啟用 HTTP/2 多路復用,合並收益降低,可視業務場景決定是否啟用。