我是山姆鍋

要讓網頁存取加快有很多技巧,其中之一就是減少 HTTP 的請求數量。由於瀏覽器允許同時發出的 HTTP 請求有數量的限制,藉由減少請求數量,可以減少等待請求完成時間以達到加速網頁存取目的。本文山姆鍋將分享如何使用 Jekyll Asset Pipeline 插件來減少並且迷你化 CSS/JS 檔案。

安裝 Jekyll Asset Pipeline 插件

這個插件是透過 Ruby Gem 安裝,在命令列執行:

1
$ gem install jekyll-asset-pipeline

壓縮 JavaScript 以及 CSS 檔案時,需要用到 YUI Compressor,按照下列指令安裝:

1
$ gem install yui-compressor

在 Gemfile 中的’:development’ group,加入下列項目:

1
2
gem "jekyll-asset-pipeline"
gem "yui-compressor"

安裝 Jekyll Asset Pipeline 插件

在 Octopress 的 plugins 目錄中,新增名為’jekyll_asset_pipeline.rb’的檔案,內容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
require 'jekyll_asset_pipeline'

module JekyllAssetPipeline

class CssCompressor < JekyllAssetPipeline::Compressor
require 'yui/compressor'

def self.filetype
'.css'
end

def compress
return YUI::CssCompressor.new.compress(@content)
end
end

class JavaScriptCompressor < JekyllAssetPipeline::Compressor
require 'yui/compressor'
#require 'closure-compiler'

def self.filetype
'.js'
end

def compress
return YUI::JavaScriptCompressor.new(munge: true).compress(@content)
#return Closure::Compiler.new.compile(@content)
end
end

end

匯整並迷你化 CSS/JS 檔案

這個步驟需要修改的檔案會根據您使用的樣版 (template) 而定,一般是修改下列檔案:

1
2
3
source/_include/head.html
source/_include/custom/head.html
source/_include?custom/after_footer.html

把要匯整成同一個檔案的 CSS 檔案,按照下列方式指定:

1
2
3
4
5
6
7
8
9
{% css_asset_tag global %}
- /_assets/styles/aqpb-view.css
- /_assets/styles/frontend.css
- /_assets/styles/foundation.min.css
- /_assets/styles/options.css
- /_assets/styles/app.css
- /_assets/styles/responsive.css
- /_assets/styles/colorbox.css
{% endcss_asset_tag %}

其中,‘global’是產出的 CSS 檔名前綴,產出的檔案名稱後面還會加上版號。檔名看起來會像是’global-dd5a45262af5235d70403ad9ed37adcc.css’,並放置在’public/assets’目錄中。Jekyll Asset Pipeline 會在 HTML 幫我們設定好來加載這個 CSS 檔。

把要匯整成同一個檔案的 JS 檔,按照下列方式指定:

1
2
3
4
{% javascript_asset_tag global %}
- /_assets/scripts/jquery.min.js
- /_assets/scripts/app.js
{% endjavascript_asset_tag %}

其中,‘global’是產出檔名的前綴,產生的 JS 檔明類似’global-b4c189f3acc9945b3087071a918a4844.js’。同樣地,Jekyll Asset Pipeline 插件會幫我們設定