`
gogo1217
  • 浏览: 150204 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

使用yuicompressor压缩及合并js,css静态资源

阅读更多

版权所有,转载请注明来源http://gogo1217.iteye.com,违者必究!

 

      在做WEB企业应用时,都会涉及到的CSS和JS的编写。随着项目的推进,这些文件如果写在同一个文件中,造成维护的困难,找一个需要修改的地方很麻烦。所以,好的做法是根据JS的功能划分为多个小的JS文件,页面通过某种方式间接引用这些小的JS文件。

       这里推荐yahoo的一个js/css压缩工具YUI Compressor ,目前最新版本是2.4.6。

1.下载文件后,新建工程目录如下所示:

2.ant脚本及配置文件如下:

ant脚本build.xml文件代码如下:

由于在实际项目中,我们需要对不同的目录的资源文件压缩,因此一般通过循环完成多个目录的压缩。在本配置文件中,使用了额外的一个ant任务扩展包ant-contrib,下载地址为:http://ant-contrib.sourceforge.net/. 该包在ant的基础上扩展了多个自定义任务。

<?xml version="1.0" encoding="UTF-8"?>
<project name="yui-compressor-demo" basedir="." default="yui-compress">
	<description>
		yui-compressor-demo create by gogo1217 2011-9-4
		http://gogo1217.iteye.com/
	</description>

	<!--导入配置文件 -->
	<property file="build.properties" />
	<tstamp>
		<format property="build.time" pattern="yyyy-MM-dd-HH-mm" />
	</tstamp>

	<!--设置ant-contrib.jar用于逻辑判断 -->
	<taskdef resource="net/sf/antcontrib/antlib.xml">
		<classpath>
			<pathelement location="${lib.build.antcontrib}" />
		</classpath>
	</taskdef>

	<!--设置编译环境 -->
	<path id="build.classpath">
		<fileset dir="${lib.build}">
			<include name="*.jar" />
		</fileset>
	</path>

	<!-- 创建build相关目录 -->
	<target name="init">
		<delete dir="${deploy.dir}" />
		<mkdir dir="${deploy.resource}" />
	</target>

	<!--压缩合并css、js文件 -->
	<target name="yui-compress" depends="init">
		<!-- 由于需要对css和js压缩,因此使用antcontrib ant扩展来做循环判断 -->
		<for list="${resources.include}" param="resoucesPath">
			<!-- param表示在迭代的变量,使用时为@{resourcesPath} -->
			<sequential>
				<!--创建资源目录 -->
				<mkdir dir="${deploy.resource}/@{resoucesPath}/" />
				<!--合并小文件为一个资源文件 -->
				<concat
					destfile="${deploy.resource}/@{resoucesPath}/demo-src.@{resoucesPath}"
					fixlastline="true" encoding="UTF-8">
					<fileset dir="${resource.dir}/@{resoucesPath}">
						<exclude name="demo.@{resoucesPath}" />
					</fileset>
				</concat>
				<!--压缩资源文件 -->
				<apply executable="java" parallel="false" failonerror="true">
					<fileset dir="${deploy.resource}/@{resoucesPath}">
						<include name="*.@{resoucesPath}" />
					</fileset>
					<arg line="-jar" />
					<arg path="${lib.build.yuicompressor}" />
					<arg line="--charset UTF-8" />
					<srcfile />
					<arg line="-o" />
					<mapper type="glob" from="*.@{resoucesPath}"
						to="${deploy.resource}/@{resoucesPath}/demo-min.@{resoucesPath}" />
					<targetfile />
				</apply>
			</sequential>
		</for>
	</target>
</project>

 build.properties配置文件代码如下:

##工程根目录
project.dir=..

##app目录
resource.dir=${project.dir}/resources
resources.include=css,js

##依赖包
lib.dir = ${project.dir}/lib
lib.build=${lib.dir}/build
lib.build.yuicompressor= ${lib.dir}/build/yuicompressor-2.4.6.jar
lib.build.antcontrib= ${lib.dir}/build/ant-contrib-1.0b3.jar

#发布目录
deploy.dir=${project.dir}/deploy
deploy.resource=${deploy.dir}/resources

  3.在build.xml上右键,选择“Run-As”-》“Ant Build”,控制台结果为:

4.工程中新建了目录deploy及相关的子目录如下所示:

其中 demo-src.css和demo-src.js为压缩后的源文件,发布时,带上源文件便于使用者能覆盖重写和查找问题。demo-min.css和demo-min.js为压缩后的代码。

demo-src.js源码如下:

/**
 * @description mi命名空间
 * @namespace mi命名空间
 * @version 0.1
 */
var mi = {
	/**
	 * 设置cookie
	 *
	 * @param {String}
	 *            name cookie name
	 * @param {Object}
	 *            value cookie value
	 * @param {Number}
	 *            days 保持天数,单位天 0表示永久不实效,小于0表示立马实效
	 */
	setCookie : function(name, value, days) {
		if(name && value) {
			var expires = '';
			if(days) {
				var d = new Date();
				d.setTime(d.getTime() + days * 24 * 60 * 60 * 1000);
				expires = '; expires=' + d.toGMTString();
			}
			document.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/';
		}
	},
	/**
	 * 读取cookie
	 *
	 * @param {String}
	 *            sName cookie内的名称
	 * @returns {Object} 该cookie的内容
	 */
	getCookie : function(name) {
		var cookieValue = null;
		if(document.cookie && document.cookie != '') {
			var cookies = document.cookie.split(';');
			for(var i = 0; i < cookies.length; i++) {
				var cookie = jQuery.trim(cookies[i]);
				if(cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	},
	/**
	 * 删除cookie
	 *
	 * @param {String}
	 *            name 所要删除cookie中的名称
	 */
	removeCookie : function(name) {
		this.setCookie(name, '', -1);
	}
};

/**
 * @namespace 表单相关
 * @version 0.1
 */
mi.form = {
};

 demo-min.js源码如下:

var mi={setCookie:function(b,c,f){if(b&&c){var a="";if(f){var e=new Date();
e.setTime(e.getTime()+f*24*60*60*1000);a="; expires="+e.toGMTString()}
document.cookie=b+"="+encodeURIComponent(c)+a+"; path=/"}},
getCookie:function(a){var e=null;if(document.cookie&&document.cookie!="")
{var d=document.cookie.split(";");for(var c=0;c<d.length;c++)
{var b=jQuery.trim(d[c]);if(b.substring(0,a.length+1)==(a+"="))
{e=decodeURIComponent(b.substring(a.length+1));break}}}return e},
removeCookie:function(a){this.setCookie(a,"",-1)}};mi.form={};

       由于排版问题,因此本是一行现实的demo-min.js被换行成多行了。

 

压缩的好处

       上面对比可以看出yui-compress能将删除 全部 注释、 换行和 多余的 空白字符 ,并且将中间变量简化为单个字符 ,从而大大的减少js和css文件的体积。将页面的资源文件压缩在一个文件中,从而减少页面的请求次数,也减少了服务器的压力和提高了页面的相应速度,是页面的优化的一项重要的措施。

 

文件拆分后页面引入的统一措施

      由于将css和js文件拆分为多个文件,如果不做处理,开发时页面的需要引入多个文件,但在发布时确只需要引入单个文件。为了统一开发和发布的环境,css可以通过@import命令达到统一,而js可以通过js添加javascript标签动态引入所拆分的小的js达到统一,如在本例中,页面只需要引入demo.css和demo.js即可。

      在实际开发中,可能还会遇到不同的页面引入不同的css,但是又会引入共同的css的情况,这均可以通过concat命令生成单个文件完成。

      demo.css示例

@import url(00-clean.css);
@import url(01-global.css);
@import url(02-form.css);

     demo.js示例

getContextPath = function() {
	var contentPath = '';
	var link = document.getElementsByTagName('script');
	for(var q = 0; q < link.length; q++) {
		var h = !!document.querySelector ? link[q].src : link[q].getAttribute("src", 4), i;
		if(h && ( i = h.indexOf('resources/js/demo.js')) >= 0) {
			var j = h.indexOf('://');
			contentPath = j < 0 ? h.substring(0, i - 1) : h.substring(h.indexOf('/', j + 3), i - 1);
			return contentPath;
		}
	};
	return contentPath;
}
importJS = function(url) {
	document.write('<script type="text/javascript" src="' + getContextPath() + '/resources/js/' + url + '"></script>');
}
importJS('00-common.js');
importJS('11-form.js');

 

本文中的实例工程打包下载:

yui-compressor-demo.rar (991 KB) 

 

  • 大小: 24.1 KB
  • 大小: 15 KB
  • 大小: 12.9 KB
2
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics