1. 程式人生 > >【js&css檔案壓縮】php+minify+nginx 的配置和使用 -1

【js&css檔案壓縮】php+minify+nginx 的配置和使用 -1

最近沒有更新部落格,並不是因為沒有學習,而是因為沒有學到一定程度。不過有些比較工具類的知識卻可以拿來小結一下,比如這次所說的檔案壓縮。
我們都知道web伺服器在處理這樣的靜態檔案如圖片,js,css的時候所需要的等待時間是十分長的。因此出現了許多的技術來減少傳送時間。大家都有接觸過xxx.min.js或者xxx.min.css這類的檔案.這些檔案儲存在伺服器上.表示已經被工具進行壓縮了.不過我們也可以通過伺服器指令碼將請求的css檔案或者js檔案壓縮後傳送。這就是我們要說的minify模組。
minify是一個開源的github專案,可以點選檢視專案地址
至於php與nginx的配置可以參考網路上其他的教程,我們這裡就不多介紹。當然可以使用apache或其他伺服器。
關於minify的目錄如下圖所示:
minify-master目錄


這裡我們可以閱讀README.txt和MIN.txt。裡面有一定的介紹。
如果需要進行版本升級可以閱讀UPGRADING.txt。
我們將min資料夾拷貝到網站根目錄(目錄可自定),這時候可以通過http://localhost/min/ 就能訪問到min資料夾下的index.php檔案。
如果使用了某某框架導致無法訪問min資料夾下的xxx.php檔案,可以設定rewrite機制開啟訪問(暫無具體寫法)。接下來我們要做的就是閱讀一下index.php檔案
Index.php

<?php
/**
 * Front controller for default Minify implementation
 * 
 * DO NOT EDIT! Configure this utility via config.php and groupsConfig.php
 * 
 * @package
Minify */
define('MINIFY_MIN_DIR', dirname(__FILE__)); // set config path defaults 配置檔案分別是正式用,測試用以及檔案組合用 $min_configPaths = array( 'base' => MINIFY_MIN_DIR . '/config.php', 'test' => MINIFY_MIN_DIR . '/config-test.php', 'groups' => MINIFY_MIN_DIR . '/groupsConfig.php' ); // check for custom config paths
if (!empty($min_customConfigPaths) && is_array($min_customConfigPaths)) { $min_configPaths = array_merge($min_configPaths, $min_customConfigPaths); } // load config 讀取配置檔案 require $min_configPaths['base']; // 如果請求中包含 test的關鍵字 則使用test-config 配置 if (isset($_GET['test'])) { include $min_configPaths['test']; } require "$min_libPath/Minify/Loader.php"; Minify_Loader::register(); Minify::$uploaderHoursBehind = $min_uploaderHoursBehind; Minify::setCache( isset($min_cachePath) ? $min_cachePath : '' ,$min_cacheFileLocking ); // 壓縮檔案的根目錄 可在config.php檔案中配置 預設為網站根目錄 if ($min_documentRoot) { $_SERVER['DOCUMENT_ROOT'] = $min_documentRoot; Minify::$isDocRootSet = true; } $min_serveOptions['minifierOptions']['text/css']['symlinks'] = $min_symlinks; // auto-add targets to allowDirs foreach ($min_symlinks as $uri => $target) { $min_serveOptions['minApp']['allowDirs'][] = $target; } if ($min_allowDebugFlag) { $min_serveOptions['debug'] = Minify_DebugDetector::shouldDebugRequest($_COOKIE, $_GET, $_SERVER['REQUEST_URI']); } if ($min_errorLogger) { if (true === $min_errorLogger) { $min_errorLogger = FirePHP::getInstance(true); } Minify_Logger::setLogger($min_errorLogger); } // check for URI versioning if (preg_match('/&\\d/', $_SERVER['QUERY_STRING']) || isset($_GET['v'])) { $min_serveOptions['maxAge'] = 31536000; } // need groups config? 請求為g 檔案組合 if (isset($_GET['g'])) { // well need groups config $min_serveOptions['minApp']['groups'] = (require $min_configPaths['groups']); } // serve or redirect if (isset($_GET['f']) || isset($_GET['g'])) { if (! isset($min_serveController)) { $min_serveController = new Minify_Controller_MinApp(); } Minify::serve($min_serveController, $min_serveOptions); } elseif ($min_enableBuilder) { header('Location: builder/'); exit; } else { header('Location: /'); exit; } // 不存在f或者g請求 則不輸出任何內容

我們需要配置和檢視一下config.php檔案
config.php

<?php
/**
 * Configuration for "min", the default application built with the Minify
 * library
 * 
 * @package Minify
 */


/**
 * Allow use of the Minify URI Builder app. Only set this to true while you need it.
 */
$min_enableBuilder = false;

/**
 * If non-empty, the Builder will be protected with HTTP Digest auth.
 * The username is "admin".
 */
$min_builderPassword = 'admin';


/**
 * Set to true to log messages to FirePHP (Firefox Firebug addon).
 * Set to false for no error logging (Minify may be slightly faster).
 * @link http://www.firephp.org/
 *
 * If you want to use a custom error logger, set this to your logger
 * instance. Your object should have a method log(string $message).
 */
$min_errorLogger = false;


/**
 * To allow debug mode output, you must set this option to true.
 *
 * Once true, you can send the cookie minDebug to request debug mode output. The
 * cookie value should match the URIs you'd like to debug. E.g. to debug
 * /min/f=file1.js send the cookie minDebug=file1.js
 * You can manually enable debugging by appending "&debug" to a URI.
 * E.g. /min/?f=script1.js,script2.js&debug
 * 
 * In 'debug' mode, Minify combines files with no minification and adds comments
 * to indicate line #s of the original files.
 */
$min_allowDebugFlag = true; //開啟除錯,可以在瀏覽器檢視錯誤資訊,正式用時需要關閉


/**
 * For best performance, specify your temp directory here. Otherwise Minify
 * will have to load extra code to guess. Some examples below:
 */
$min_cachePath = 'c:\\WINDOWS\\Temp'; //這裡我將minify生成的壓縮檔案快取到了指定的資料夾下
//$min_cachePath = '/tmp';
//$min_cachePath = preg_replace('/^\\d+;/', '', session_save_path());

/**
 * To use APC/Memcache/ZendPlatform for cache storage, require the class and
 * set $min_cachePath to an instance. Example below:
 */
//require dirname(__FILE__) . '/lib/Minify/Cache/APC.php';
//$min_cachePath = new Minify_Cache_APC();


/**
 * Leave an empty string to use PHP's $_SERVER['DOCUMENT_ROOT'].
 *
 * On some servers, this value may be misconfigured or missing. If so, set this 
 * to your full document root path with no trailing slash.
 * E.g. '/home/accountname/public_html' or 'c:\\xampp\\htdocs'
 *
 * If /min/ is directly inside your document root, just uncomment the 
 * second line. The third line might work on some Apache servers.
 */
 //設定了目標壓縮檔案的起始目錄
$min_documentRoot = $_SERVER['DOCUMENT_ROOT'].'/Public';
//$min_documentRoot = substr(__FILE__, 0, -15);
//$min_documentRoot = $_SERVER['SUBDOMAIN_DOCUMENT_ROOT'];


/**
 * Cache file locking. Set to false if filesystem is NFS. On at least one 
 * NFS system flock-ing attempts stalled PHP for 30 seconds!
 */
$min_cacheFileLocking = true;


/**
 * Combining multiple CSS files can place @import declarations after rules, which
 * is invalid. Minify will attempt to detect when this happens and place a
 * warning comment at the top of the CSS output. To resolve this you can either 
 * move the @imports within your CSS files, or enable this option, which will 
 * move all @imports to the top of the output. Note that moving @imports could 
 * affect CSS values (which is why this option is disabled by default).
 */
$min_serveOptions['bubbleCssImports'] = false;


/**
 * Cache-Control: max-age value sent to browser (in seconds). After this period,
 * the browser will send another conditional GET. Use a longer period for lower
 * traffic but you may want to shorten this before making changes if it's crucial
 * those changes are seen immediately.
 *
 * Note: Despite this setting, if you include a number at the end of the
 * querystring, maxAge will be set to one year. E.g. /min/f=hello.css&123456
 */
$min_serveOptions['maxAge'] = 1800;//設定客戶端快取的時間長度 1800/60/60=0.5h


/**
 * To use CSSmin (Túbal Martín's port of the YUI CSS compressor), uncomment the following line:
 */
//$min_serveOptions['minifiers']['text/css'] = array('Minify_CSSmin', 'minify');


/**
 * To use Google's Closure Compiler API to minify Javascript (falling back to JSMin
 * on failure), uncomment the following line:
 */
//$min_serveOptions['minifiers']['application/x-javascript'] = array('Minify_JS_ClosureCompiler', 'minify');


/**
 * If you'd like to restrict the "f" option to files within/below
 * particular directories below DOCUMENT_ROOT, set this here.
 * You will still need to include the directory in the
 * f or b GET parameters.
 * 
 * // = shortcut for DOCUMENT_ROOT 
 */
//$min_serveOptions['minApp']['allowDirs'] = array('//js', '//css');

/**
 * Set to true to disable the "f" GET parameter for specifying files.
 * Only the "g" parameter will be considered.
 */
$min_serveOptions['minApp']['groupsOnly'] = false;


/**
 * By default, Minify will not minify files with names containing .min or -min
 * before the extension. E.g. myFile.min.js will not be processed by JSMin
 * 
 * To minify all files, set this option to null. You could also specify your
 * own pattern that is matched against the filename.
 */
//$min_serveOptions['minApp']['noMinPattern'] = '@[-\\.]min\\.(?:js|css)[email protected]';


/**
 * If you minify CSS files stored in symlink-ed directories, the URI rewriting
 * algorithm can fail. To prevent this, provide an array of link paths to
 * target paths, where the link paths are within the document root.
 * 
 * Because paths need to be normalized for this to work, use "//" to substitute 
 * the doc root in the link paths (the array keys). E.g.:
 * <code>
 * array('//symlink' => '/real/target/path') // unix
 * array('//static' => 'D:\\staticStorage')  // Windows
 * </code>
 */
$min_symlinks = array();


/**
 * If you upload files from Windows to a non-Windows server, Windows may report
 * incorrect mtimes for the files. This may cause Minify to keep serving stale 
 * cache files when source file changes are made too frequently (e.g. more than
 * once an hour).
 * 
 * Immediately after modifying and uploading a file, use the touch command to 
 * update the mtime on the server. If the mtime jumps ahead by a number of hours,
 * set this variable to that number. If the mtime moves back, this should not be 
 * needed.
 *
 * In the Windows SFTP client WinSCP, there's an option that may fix this 
 * issue without changing the variable below. Under login > environment, 
 * select the option "Adjust remote timestamp with DST".
 * @link http://winscp.net/eng/docs/ui_login_environment#daylight_saving_time
 */
$min_uploaderHoursBehind = 0;


/**
 * Path to Minify's lib folder. If you happen to move it, change 
 * this accordingly.
 */
$min_libPath = dirname(__FILE__) . '/lib';


// try to disable output_compression (may not have an effect)
ini_set('zlib.output_compression', '0');

我們所需要修改的可能就是原始檔目錄($_min_documentRoot)
和壓縮檔案快取目錄($_min_cachePath)
準備完成後我們可以找一些比較常用的檔案來進行壓縮吧。
我的配置
config.php: $_min_documentRoot=根目錄/Public

例子1:普通js檔案壓縮
檔案 : jquery.js 大小 (256,592 位元組)
檔案目錄:根目錄/Public/js/jquery.js

訪問地址: http://localhost/min/?f=js/jquery.js
目標檔案大小: (37,793位元組)
官網min檔案大小: (84,320 位元組)
很明顯我們壓縮的大小比官網的還要寫,因此必須要測試是否能夠正常使用這個js檔案。
測試開始:(簡單測試)
jquery測試
我們發現$符號能夠正確使用jquery的dom操作。同時載入的時候並沒有出現錯誤.因此我們壓縮的檔案是可以使用的。

例子2:普通css檔案壓縮
檔案: bootstrap.css 大小 (148,206 位元組)
檔案目錄:根目錄/Public/css/bootstrap.css
訪問地址:http://localhost/min/?f=css/bootstrap.css
目標檔案大小:(19,617位元組)
說明我們的css檔案也成功的壓縮了好幾倍.

例子3:組合式壓縮js檔案
如果沒有使用g請求,我們也是可以通過f請求做多個檔案組合壓縮
檔案: jquery.js + underscore.js
jquery.js 大小 (256,592 位元組)
underscore.js 大小 (54,537 位元組)
訪問地址:http://localhost/min/?f=js/jquery.js,underscore.js
目標檔案大小:(44,660位元組)
測試是否能使用該js
測試組合壓縮js
結果是可以被壓縮,並且能夠正常使用。

例子4:組合式壓縮css檔案
同樣,我們不使用g請求,通過f請求來對多個css檔案進行壓縮
檔案:bootstrap.css + bootstrap.theme.css
bootstrap.css 大小 (148,206 位元組)
bootstrap-theme.css 大小 (23,084 位元組)
訪問地址:http://localhost/min/?f=css/bootstrap.css,css/bootstrap-theme.css
目標檔案大小:(21,822 位元組)

例子5:使用g請求進行壓縮js檔案
我們需要通過編輯groupsConfig.php 檔案

<?php
/**
 * Groups configuration for default Minify implementation
 * @package Minify
 */

/** 
 * You may wish to use the Minify URI Builder app to suggest
 * changes. http://yourdomain/min/builder/
 *
 * See http://code.google.com/p/minify/wiki/CustomSource for other ideas
 **/

return array(
    // 'js' => array('//js/file1.js', '//js/file2.js'),
    // 'css' => array('//css/file1.css', '//css/file2.css'),
);

在reutrn array(); 裡面填寫關鍵的鍵名和鍵值,鍵值則是多個檔案路徑組合在一起.如果是以/開頭或者以//開頭則是從制定好的min_documentRoot開始。當然可以使用絕對路徑或者../方式向上尋找
檔案 jquery.js + underscore.js + backbone.js
jquery.js 大小 (256,592 位元組)
underscore.js 大小 (54,537 位元組)
backbone.js 大小 (36,200 位元組)
訪問地址: http://localhost/min/?g=mvc
目標檔案大小: (50,951位元組)
測試使用情況
mvc元件
結果表明壓縮後並沒有影響js的使用
配置檔案如下:

return array(
     'mvc' => array('//js/jquery.js', '//js/underscore.js','//js/backbone.js'),
);

大致的例子已經說完,接下來說一些額外的知識.

  1. 除錯模式
    如果我們想要進入除錯模式的話,(debug)我們可以在請求的尾部新增一個引數&debug=1。同時在config.php裡面將$min_allowDebugFlag設定為true;
    這樣我們的響應結果會如下所示:
    測試模式
    內容前面都會有一個行號表示 同時標示來自哪一個檔案。
  2. 檔案過期
    一般得到的檔案的過期時長為30分鐘,在config.php中的
    $min_serveOptions[‘maxAge’] 有設定,如果想要將過期長度設定為1年(最大為一年),可以在請求引數中新增&123456 任意數字或者&v 都可行.最好通過數字的不同來確認原始檔的修改。

在這裡我們主要介紹了minify的使用,如果大家十分喜歡這個外掛,可以在上面的開源專案連結中下載這個模組。實際上這個模組還有許多的東西可以說,如果你願意去了解裡面的內容的話。雖然響應的檔案都成功的被壓縮,但是伺服器的處理效率以及瀏覽器的處理效率並沒有進行分析。所以實際上我的任務並沒有結束,等再介紹一個新的壓縮處理技術後再來進行分析.

相關推薦

js&css檔案壓縮php+minify+nginx配置使用 -1

最近沒有更新部落格,並不是因為沒有學習,而是因為沒有學到一定程度。不過有些比較工具類的知識卻可以拿來小結一下,比如這次所說的檔案壓縮。 我們都知道web伺服器在處理這樣的靜態檔案如圖片,js,css的時候所需要的等待時間是十分長的。因此出現了許多的技術來減少傳

JS代碼壓縮使用YUI Compressor對js文件進行壓縮處理

js代碼 bird spell 說明 ber enum ide relative auto 概述在使用html5開發Hybird APP的時候,可能會引入大量的js包,另外對於一些核心的js文件,進行一些特殊的處理,如壓縮和加密就顯得很重要了,YUI Compressor就

安裝及使用YUICompressor(壓縮JS,CSS檔案)4

環境:Windows 7(Win 8也可) Java 版本:1.4以上皆可。 1.需要下載的檔案: Ant.                         http://ant.apache.org/bindownload.cgi  選擇apache-ant-1.9.

php模版檔案html檔案中引入js,css檔案錯誤解決

1,html檔案引入js一些資原始檔時候:可以寫相對路徑來引入,<script src="../lib/layer/layer.js"></script>     <script  src="../lib/jquer.min.js">&l

關於共享的js,css檔案

前端成熟外掛很多,一般是一個js,一個css檔案。外掛可以下載並製作成自己MVC框架的工具庫。自己也可以將不常變動的Js,css整理到一起,並在公共檔案中引用。比如前端檢視可以如下引用排版 @{     Layout = "~/Views/Shared/_RetailLayo

Luogu P1558 色板遊戲線段樹/狀態壓縮By cellur925

題目傳送門 今天非常想再看一遍霸王別姬想不進去題於是開始刷資料結構 注意到至多隻有\(30\)種顏色,啊啊啊啊我一開始竟然想的不是狀態壓縮而是線上段樹中存一個30大小的陣列,這樣每次更新的時候暴力迴圈一遍。hhhhh。 可能這樣比較好想吧,但是比正解狀態壓縮一下不知道差到哪裡去了:)。開始還智障地把每次

Azure .net WebAPP的js/css檔案過大導致訪問慢的解決辦法

https://docs.azure.cn/zh-cn/articles/azure-operations-guide/app-service-web/aog-app-service-web-qa-js-or-css-file-too-large-cause-slower-access  &nbs

js每日一練京東無延遲選單

1、mouseenter和mouseover的區別使用mouseover/mouseout時,如果滑鼠從父元素移動到子元素上,即便沒有離開父元素,也會觸發父元素的mouseout事件使用mouseenter/mouseleave時,如果滑鼠沒有離開父元素,在其子元素上任意移動,也不會觸發mouseleave事

js每日一練京東無延遲菜單

mouseout 移動 元素移動 sele 觸發 每日一練 .data 京東 原生js 1、mouseenter和mouseover的區別使用mouseover/mouseout時,如果鼠標從父元素移動到子元素上,即便沒有離開父元素,也會觸發父元素的mouseout事件使用

js每日一練移動端滑屏互動

一、知識點1、em && rem && vw/vhem:根據當前樣式裡面定義的font-size大小來計算,如當前樣式裡面沒定義font-size,那麼就根據父級上的font-size大小來計算如:.box{font-size:20px; //此時1em=20pxheight:

js每日一練移動端滑屏交互

2.0 窗口大小 變化 當前 成了 ont 3.2 屏幕寬度 amp 一、知識點1、em && rem && vw/vhem:根據當前樣式裏面定義的font-size大小來計算,如當前樣式裏面沒定義font-size,那麽就根據父級上的fon

宇潤日常瘋測-005PHP 中的 clone new 效能比較

clone和new本不應該放在一起比較,它們的作用是不同的。但可能有一些場景下,可以用clone也可以用new,那麼這時候我們選哪個呢? 我編寫了兩個測試,第一個是宣告一個空類,第二個是帶構造方法、屬性的類。另外,我還加入了 PHP 序列化的測試。 國際慣例,直接上程式碼,一目瞭然。 程式碼 <?php

hdu 3605 Escape網路流+狀態壓縮

有n個人要移居m個星球,給出每個合適的星球,每個星球最多能容納的人數,問是否所有人都可以移居。(1≤N≤105,1≤M≤10)(1≤N≤105,1≤M≤10)  最多有十個星球,而N很大,所以可能會有很多重複,因為每個人去哪個星球最多有2^10中情況,所以可以壓縮點

SpringBoot Boostrap前端js/css檔案配置

感謝作者的分享:https://www.cnblogs.com/smiler/p/6857213.html http://blog.csdn.net/isea533/article/details/50412212 1.按理SpringBoot會自動載入resources

關於修改js,css檔案瀏覽器端未改變的原因及解決辦法

今天本人對服務端的js進行了改動,執行之後發現瀏覽器端的js並未發生改變。 本人於是開始分析問題所在  首先檢視workspace中js是否改動,檢視結果:已改變  第二步嘗試 tomcat clean,delete操作,結果:無效 第三步檢視釋出路徑下 

js事件詳解js事件封裝函式,js跨瀏覽器事件處理機制

一、事件流 事件流描述的是從頁面中接受事件的順序。 IE的事件流是事件冒泡流,而Netscape的事件流是事件捕獲流 1、事件冒泡 事件冒泡,即事件最開始由最具體的元素(文件中巢狀層次最深的那個節點)接收,然後逐級向上轉播至最不具體的節點(文件)。 2、事件捕獲 事件捕獲的

nginx 部署 vue 專案找不到js css檔案

很多時候 npm run build 之後, index.html 檔案中webpack 自動插入的 js 檔案 css 檔案的相對目錄總是不對,釋出到伺服器上之後,nginx 找不到檔案。 [email protected] 在 [email protec

js高程學習筆記關於變數值函式引數

變數包含了兩種不同型別的值: 基本型別 (Undefined、null、Boolean、Number、string都屬於基本型別) 引用型別 (物件) 兩種值在賦值上不同的是: 將一個引用型別的值(物件)賦值給一個變數,可以為其新增/刪除屬性和方法。 但如果是一個基本型別的值是不可以

關於Django中修改js css檔案但瀏覽器無法及時與之改變的問題

今天修改之前實習小夥伴寫的js程式碼的時候,遇到修改後頁面未發生變化的問題。因為我是web開發小白,所以上網查了一波,得以解決~~ 初次進行web工程開發的人可能會碰到這樣的情況:自己在明明對工程上的某個js或css檔案進行了修改,並提交到伺服器上去了

支付寶小程式PHP 獲取使用者敏感資訊手機號 驗籤解密 RSA解密 AES解密

需求 支付寶小程式端,獲取到加密的使用者手機號資料,需要經過服務端對資料進行解密,得到使用者的手機號 問題 使用者資訊為敏感資訊,需要用到敏感資訊加密解密方法中的方式進行解密 服務端為PHP,由於官方沒有對應的演示demo,經過摸索測試,還是出現了驗籤不通過,並且解密不成