網頁速度慢除目前看起來最大問題就是 http request 數量太多,因為每次的 request 都需要一定的時間,如果能夠壓縮在同一個 request 是最棒的狀況,前面幾篇有把 Javascript 用 uglify 把檔案壓成一支,以及把小的圖片轉換為 data uri 隨著 html/css 一同載入,這次要做的是把 CSS 直接以 <style> tag 直接塞入 html 的 head 中,讓 CSS 的隨著 html 一起載入,請小心使用
這次的 script 一樣是由 coffeeScript 寫成,以及使用 cheerio 來作 dom select
立馬下載使用
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fs = require('fs') | |
cheerio = require('cheerio') | |
staticFolder = 'static' | |
cssFolder = 'css' | |
cssRoot = __dirname + '/' + cssFolder | |
htmlFolder = 'views' | |
htmlRoot = __dirname + '/../application/' + htmlFolder | |
skipFiles = ['.DS_Store', 'mail'] | |
Core = module.exports = | |
getFileList: (folderPath = null, cb) -> | |
console.log 'getFileList begin ', arguments | |
return null unless folderPath | |
return fs.readdirSync(folderPath) unless cb | |
fs.readdir folderPath, (err, files) -> | |
(if (err) then cb(null) else cb(files)) | |
getFile: (path = null, cb) -> | |
console.log 'getFile begin ', arguments | |
return null unless path | |
unless cb | |
f = fs.readFileSync(path) | |
if f | |
return f.toString() | |
else | |
return null | |
fs.readFile path, (err, data) -> | |
(if (err) then cb(null) else cb(data.toString())) | |
saveFile: (path = null, data = null, cb) -> | |
console.log 'saveFile begin ', arguments | |
return null unless path | |
return null unless data | |
if typeof(data) is 'string' | |
data = new Buffer(data, 'utf8') | |
unless cb | |
return fs.writeFileSync(path, data) | |
fs.writeFile path, data, (err) -> | |
if(err) | |
console.log 'err = ' ,err | |
else | |
console.log 'save success = ', path | |
htmlPaths = Core.getFileList(htmlRoot) | |
for i of htmlPaths | |
htmlPath = htmlPaths[i] | |
if skipFiles.indexOf(htmlPath) >= 0 | |
continue | |
htmlPath = htmlRoot+ '/' + htmlPath | |
html = Core.getFile(htmlPath) | |
$ = cheerio.load(html) | |
style = '' | |
$('link').each (index, item)=> | |
$item = $(item) | |
src = $item.attr('href') | |
srcArray = src.split('/') | |
src = cssRoot + '/' + srcArray[srcArray.length-1] | |
style += Core.getFile(src) + '\n' | |
if style.length is 0 | |
continue | |
$('head').append('<style>\n' + style + '</style>\n') | |
Core.saveFile(htmlPath, $.html()) | |
相關連結
image in csshtml from url to uri
html script tags combined a js flie
uglify
coffeeScript
cheerio
沒有留言:
張貼留言