实例文件结构
1.index.html为入口html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Require</title>
<script type="text/javascript" src="require.js" data-main="config.js"></script>
</head>
<body>
<div id="app">
hello require;
</div>
</body>
</html>
index.html加载完require.js后,会加载文件中的data-main属性中的js文件。require.js源码下载
2. data-main属性中config.js文件
/**
* 前端项目的配置,每个项目需要修改此文件,主要配置包括压缩的css路径,自定义资源文件路径映射等等
*/
require.config({
waitSeconds: 7,
paths: {
'com/develop': 'dev'
},
deps: ['main']
});
console.log("the config.js has been loaded");
config.js文件配置了模块加载的参数,waitSeconds定义了当前模块的依赖模块加载完毕的最大时间间隔;baseUrl为main.js所在的文件路径;
3. main.js文件内容
define([ 'example/module1',
'example/module2'], function(Module1, Module2) {
Module1.getMsgInModule1();
Module2.getMsgInModule2();
});
console.log("the main.js has been loaded");
- example/module1模块内容
define([ 'example/module1Child' ], function(Module1Child) {
//调用模块一的子模块
Module1Child.getMsgInModule1Child();
function getMsgInModule1() {
console.log("call getMsgInModule1");
}
return {
getMsgInModule1: getMsgInModule1
}
});
console.log("the module1.js has been loaded");
- example/module2文件
define([ 'example/module2Child', 'example/module1Child' ], function(Module2Child, Module1Child) {
Module2Child.getMsgInModule2Child();
Module1Child.getMsgInModule1Child();
function getMsgInModule2() {
console.log("call getMsgInModule2");
}
return {
getMsgInModule2: getMsgInModule2
}
});
console.log("the module2.js has been loaded");
- example/module1Child文件
define(function() {
return {
getMsgInModule1Child: function () {
console.log("call getMsgInModule1Child");
}
}
});
console.log("the module1Child.js has been loaded");
7.example/module2Child文件
define(function() {
return {
getMsgInModule2Child: function () {
console.log("call getMsgInModule2Child");
}
}
});
console.log("the module2Child.js has been loaded");
实例运行结果
- 实例运行是按照模块的加载顺序依次运行;
- example/module1和example/module2都依赖example/module1Child子模块。但是,example/module1Child子模块只被加载了一次,可以查看运行结果中the module1Child.js has been loaded信息只打印了一次。
- 模块的加载顺序
- 先加载根节点main.js;
- 加载main.js中依赖的两个子模块module1和module2;
- 加载module1的子模块module1Child;
- 加载module2的子模块module2Child;
- 模块回调函数执行顺序与加载顺序基本是反过来的