require.js
异步加载js,避免网页失去响应,
管理模块之间的依赖性,便于代码的编写和维护
下载require.js http://requirejs.org/docs/download.html
引入require.js <script src="js/require.js"></script>
<script src="js/require.js" defer async="true"></script>
async=>异步
defer=>因为ie不支持async属性,所以添加defer
加载require.js后,加载自己的代码:main.js
<script src="js/require.js" data-main="js/main"></script>
主模块依赖其他模块,使用AMD规范定义的require()函数
require(['moduleA', 'moduleB', 'moduleC'], function (moduleA, moduleB, moduleC) {
//code
})
模块加载
require.config({
baseUrl: 'js/lib',
paths: {
"jquery": "jquery.min",
//加载外网中的jquery
"jquery": "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min",
"underscore": "underscore.min",
"bootstrap": "bootstrap.min"
}
});
AMD模块的写法
自定义一个math.js
define(['jquery', 'underscore'], function($, _) {
function foo() {
//code
}
return {
foo : foo
};
});
//main.js中使用math.js
require(['math'], function(math) {
math.foo();
});
加载非AMD规范的模块
对于非规范的模块,需要先定义他们的特征
require.config({
shim: {
'underscore':{
exports: '_'
},
'backbone': {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
}
}
});
//exports输出变量名
//deps数组,表明模块的依赖性
例如jquery的插件可以这么写:
require.config({
shim: {
'jquery.scroll': {
deps: ['jquery'],
exports: 'jquery.fn.scroll'
}
}
});
异步加载js,避免网页失去响应,
管理模块之间的依赖性,便于代码的编写和维护
下载require.js http://requirejs.org/docs/download.html
引入require.js <script src="js/require.js"></script>
<script src="js/require.js" defer async="true"></script>
async=>异步
defer=>因为ie不支持async属性,所以添加defer
加载require.js后,加载自己的代码:main.js
<script src="js/require.js" data-main="js/main"></script>
主模块依赖其他模块,使用AMD规范定义的require()函数
require(['moduleA', 'moduleB', 'moduleC'], function (moduleA, moduleB, moduleC) {
//code
})
模块加载
require.config({
baseUrl: 'js/lib',
paths: {
"jquery": "jquery.min",
//加载外网中的jquery
"jquery": "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min",
"underscore": "underscore.min",
"bootstrap": "bootstrap.min"
}
});
AMD模块的写法
自定义一个math.js
define(['jquery', 'underscore'], function($, _) {
function foo() {
//code
}
return {
foo : foo
};
});
//main.js中使用math.js
require(['math'], function(math) {
math.foo();
});
加载非AMD规范的模块
对于非规范的模块,需要先定义他们的特征
require.config({
shim: {
'underscore':{
exports: '_'
},
'backbone': {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
}
}
});
//exports输出变量名
//deps数组,表明模块的依赖性
例如jquery的插件可以这么写:
require.config({
shim: {
'jquery.scroll': {
deps: ['jquery'],
exports: 'jquery.fn.scroll'
}
}
});