ffe*_*ast 6 html javascript minify google-closure-compiler
我有一个嵌入了javascript代码的HTML文件,这是一个简单的例子:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type=”text/javascript”>
// javascript code
</script>
</head>
<body>
<!-- some html -->
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
获取相同文件的最简单方法是将所有JS片段缩小到其中?
HTML文件可以是任意复杂的并且具有多个脚本片段.由于多种原因,我不需要在生成的html中将js拆分为单独的.js文件.
我们使用闭包编译器并在项目中使用grunt.
选项1: 使用html-minifier ,它可以完全满足我开箱即用的需求(https://github.com/gruntjs/grunt-contrib-htmlmin,https://github.com/kangax/html-minifier#options -快速参考)
所以 grunt 片段看起来像这样:
htmlmin: {
demo: {
options: {
removeComments: true,
collapseWhitespace: true,
minifyJS: true
},
files: {
'demo/demo.html'
}
}
}
Run Code Online (Sandbox Code Playgroud)
选项2:
按照 @Chad Killingsworth 的建议使用https://github.com/Polymer/vulcanize和https://github.com/PolymerLabs/crisper 。
看起来是最灵活的方法。此外,原始js可以存储在单独的js文件中,然后仅使用Vulcanize而不使用Crisper简单地组合成单个文件。没有机会将其合并到一个可以完成所要求的任务中。
选项 3:
Grunt 嵌入(https://www.npmjs.com/package/grunt-embed, https://github.com/callumlocke/resource-embedder)
虽然它看起来已经死了,而且只完成了 Vulcanize 能做的一部分事情,但它提供了很棒的功能,比如根据资源大小和指示需要嵌入的数据属性进行嵌入
Grunt 示例:嵌入大小小于 5KB(默认阈值)的任何外部脚本和样式表:
grunt.initConfig({
embed: {
some_target: {
files: {
'dest/output.html': 'src/input.html'
}
}
}
})
Run Code Online (Sandbox Code Playgroud)
无论文件大小如何,都会嵌入特定资源的 Html 标记
<script src="foo.js" data-embed></script>
<link rel="stylesheet" href="foo.css" data-embed>
Run Code Online (Sandbox Code Playgroud)
仅当特定资源低于特定大小时才嵌入该资源:
<script src="foo.js" data-embed="2000"></script>
<link rel="stylesheet" href="foo.css" data-embed="5KB">
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2262 次 |
| 最近记录: |