RequireJs使用

使用requireJs:

原代码:

demo.html

<html>
	<head>
		<meta charset="en">
		<style>
			#content{width: 200px;height: 200px;margin:20px auto;border: 1px solid #ddd}
		</style>
	</head>
	<body>
		<div id="content"></div>
	</body>
	<script src="src/jquery-1.9.0.min.js"></script>
	<script src="src/color.js"></script>
	<script src="src/a.js"></script>
</html>

color.js

function changeBkColor (ele) {
	var colors=["#99B898","#FECEAB","#FF847C","#E84A5F","#2A363B"];
	var colorIntervel=setInterval(function(){
		var idx=Math.floor(Math.random()*5);
		$(ele).css("background-color",colors[idx]);
	},1000)
}


a.js

changeBkColor("#content");

运行效果就是 定时切换content的背景色:

a.js里调用了color.js里的方法,所以a依赖color。color里使用了jquery选择器,color依赖了jquery

修改使用require.js

demo.html

<html>
	<head>
		<meta charset="en">
		<style>
			#content{width: 200px;height: 200px;margin:20px auto;border: 1px solid #ddd}
		</style>
	</head>
	<body>
		<div id="content"></div>
	</body>
	<script src="src/require.min.js" data-main="src/main"></script>
</html>

color.js

define(['jquery'],function($){
	var changeBkColor=function(ele){
		var colors=["#99B898","#FECEAB","#FF847C","#E84A5F","#2A363B"];
		var colorIntervel=setInterval(function(){
			var idx=Math.floor(Math.random()*5);
			$(ele).css("background-color",colors[idx]);
		},1000);
	};
	return{
		changeBkColor:changeBkColor
	}
})


a.js

define(['color'],function(color){
	color.changeBkColor("#content");
})


main.js

require.config({
    baseUrl: "src/",
    paths: {
      "jquery": "jquery-1.9.0.min",
      "a": "a",
      "color": "color",
    }
  });
require(['a'])


AMD模块的写法

define(function (){
    var add = function (x,y){
      return x+y;
    };
    return {
      add: add
    };
  });
加载方法

require(['math'], function (math){
    alert(math.add(1,1));
  });

加载非规范的模块

require.config({
    shim: {

      'underscore':{
        exports: '_'
      },
      'backbone': {
        deps: ['underscore', 'jquery'],
        exports: 'Backbone'
      }
    }
  });
require.config()接受一个配置对象,这个对象除了有前面说过的paths属性之外,还有一个shim属性,专门用来配置不兼容的模块。具体来说,每个模块要定义(1)exports值(输出的变量名),表明这个模块外部调用时的名称;(2)deps数组,表明该模块的依赖性

比如,jQuery的插件可以这样定义:

<span style="font-size:12px;">shim: {
    'jquery.scroll': {
      deps: ['jquery'],
      exports: 'jQuery.fn.scroll'
    }
  }</span>

参考文章: http://www.ruanyifeng.com/blog/2012/11/require_js.html



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值