《编写可维护的 JavaScript》读书笔记第17章:文件精简和压缩

本文介绍了两种JavaScript文件精简的方法:使用YUICompressor和ClosureCompiler。通过具体示例展示了如何利用这些工具来减少文件大小,提高网页加载速度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 文件精简(minification)

1.1 YUI Compressor

语法:

java -jar yuicompressor.jar [options] [file] -o [outputfile]

例如:

java -jar yuicompressor.jar --preserve-semi core/core.js -o core/core-min.js

使用 Ant:

<target name="minify">
    <apply executable="java" failonerror="true">
        <fileset dir="${src.dir}" includes="*.js"/>
        <mapper type="glob" from="*.js" to="${build.dir}/*-min.js"/>
        
        <arg line="-jar"/>
        <arg path="${yuicompressor}"/>
        <arg line="${yuicompressor.options}"/>
        <srcfile/>
        
        <arg line="-o"/>
        <targetfile/>
    </apply>
</target>

注:新版本的 Ant 已经废弃 <apply> 任务,可以使用 <exec> 任务或 <java> 任务,关于 <java> 任务的用法,可以参考我在第15章读书笔记中的例子。

1.2 Closure Compiler

语法:

java -jar compiler.jar [options] --js [file] --js_output_file [outputfile]

例如:

java -jar compiler.jar --compilation_level SIMPLE_OPTIMIZATIONS --js core/core.js --js_output_file core/core-min.js

使用 Ant:

<target name="minify">
    <apply executable="java" failonerror="true">
        <fileset dir="${src.dir}" includes="*.js"/>
        <mapper type="glob" from="*.js" to="${build.dir}/*-min.js"/>
        
        <arg line="-jar"/>
        <arg path="${closure}"/>
        <arg line="${closure.options}"/>
        
        <arg line="--js"/>
        <srcfile/>
        
        <arg line="--js_output_file"/>
        <targetfile/>
    </apply>
</target>

2. 文件压缩

略。

转载于:https://my.oschina.net/qczhang/blog/190856

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值