理解requirejs源码 (一)

理解requirejs源码(一)

实例文件结构

在这里插入图片描述

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");
  1. 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");
  1. 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");
  1. 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");

实例运行结果

在这里插入图片描述

  1. 实例运行是按照模块的加载顺序依次运行;
  2. example/module1和example/module2都依赖example/module1Child子模块。但是,example/module1Child子模块只被加载了一次,可以查看运行结果中the module1Child.js has been loaded信息只打印了一次。
  3. 模块的加载顺序
    1. 先加载根节点main.js;
    2. 加载main.js中依赖的两个子模块module1和module2;
    3. 加载module1的子模块module1Child;
    4. 加载module2的子模块module2Child;
  4. 模块回调函数执行顺序与加载顺序基本是反过来的
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值