PHP小技巧之JS和CSS優化工具Minify的使用方法

1、實現合併和壓縮多個JS和CSS文件的代碼javascript

 

HTML:php

<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>css

 

PHP:  代碼以下java

//輸出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);
 }jquery

 

 $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;
}優化

 

2、Minify的使用方法網站

一、從code.google.com/p/minify/下載最新版Minify並解壓縮,將"min"文件夾連同裏面的內容一塊兒複製到DOCUMENT_ROOT目錄下(即網站跟目錄)。

能夠修改文件夾名"min"

二、在"min/groupsConfig.php"裏配置g參數

代碼以下:
return array(
  // 'js' => array('//js/file1.js', '//js/file2.js'),
  // 'css' => array('//css/file1.css', '//css/file2.css'),
);

三、在網頁中按照以下方式引用就能夠了:

<script type="text/javascript" src="/min/g=js&20140519"></script>

後面的數字能夠用更新日期來做標誌,"min"和步驟1裏的名稱對應。

四、性能優化,請參考code.google.com/p/minify/wiki/CookBook

注意:

一、須要將httpd.conf裏的rewrite_module模塊開啓

二、開發過程當中,能夠將調試模式開啓,開發完畢後再將調試模式關閉,能夠利用火狐瀏覽器的firebug來查看

代碼以下:

$min_allowDebugFlag = true

相關文章
相關標籤/搜索