使用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)
}
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
}
})
define(['color'],function(color){
color.changeBkColor("#content");
})
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
379

被折叠的 条评论
为什么被折叠?



