Skip to content

Instantly share code, notes, and snippets.

@jiangtao
Created December 24, 2018 06:29
Show Gist options
  • Save jiangtao/144388c9131f74077abdccb910fb289c to your computer and use it in GitHub Desktop.
Save jiangtao/144388c9131f74077abdccb910fb289c to your computer and use it in GitHub Desktop.
Dom Extract Inner Style and Style Tag To One Style
/**
* 基于tokenizer,做页面处理
*/
const fs = require('fs')
const html = fs.readFileSync('./index.html', {
encoding: 'utf-8'
})
const $ = require('cheerio').load(html, {
withDomLvl1: false,
normalizeWhitespace: false,
xmlMode: false,
decodeEntities: false
})
const filename = process.argv.slice(3).pop() || 'index2.html'
var tags = $('*').toArray()
var styles = [], innerStyles = []
tags.forEach(function (tag) {
if (tag.tagName === 'style') {
styles.push($(tag).html())
$(tag).remove()
} else {
if (tag.attribs.id && tag.attribs.style && tag.attribs.id != 'app') {
innerStyles.push(`#app #${tag.attribs.id} {${tag.attribs.style}}`)
$(tag).removeAttr('style')
}
}
})
// console.log('result',styles, innerStyles)
var optimizeID = 'optimize'
var style = $(`#${optimizeID}`)
var content = `
/* style tag */
${styles.join('')}
/* inner style */
${innerStyles.join('')} `
$(`<style id="${optimizeID}">${content}</style>`).appendTo('head')
fs.writeFileSync(filename, $.html(), {
encoding: 'utf8'
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment