RequireJS使用小结1——for Effective JavaScript Module Loading

1. require和define的区别

The require() function is used to run immediate functionalities, while define() is used to define modules for use in multiple locations. 

  • require()——用于一次性定义的语句或模块,或立即执行的语句或模块
  • define()—— 用于可以重用的模块,可以放在不同的地方

2. 管理依赖文件的载入顺序——Managing the Order of Dependent Files

RequireJS uses Asynchronous Module Loading (AMD) for loading files. Each dependent module will start loading through asynchronous requests in the given order. Even though the file order is considered, we cannot guarantee that the first file is loaded before the second file due to the asynchronous nature. So, RequireJS allows us to use the shim config to define the sequence of files which need to be loaded in correct order. Let’s see how we can create configuration options in RequireJS.

RequireJS使用异步模块载入机制(AMD),即每个独立模块都是通过异步请求载入,就是说无法保证第一个文件在第二个文件之前先行载入,为此,RequireJS使用shim来强制定义文件载入的顺序,如以下代码:

requirejs.config({
  shim: {
    'source1': ['dependency1','dependency2'],
    'source2': ['source1']
  }
});

Under normal circumstances these four files will start loading in the given order. Here, source2 depends on source1. So, once source1 has finished loading, source2 will think that all the dependencies are loaded. However, dependency1 and dependency2 may still be loading. Using the shim config, it is mandatory to load the dependencies before source1. Hence, errors will not be generated.

上述定义表示: source2依赖于source1,只有source1完成载入后才载入source2;source1依赖于dependency1和dependency2,只有dependency1和dependency2完成载入后才载入source1,故整个载入顺序为:

                                                dependency1,dependency2(没有规定该两个文件的载入顺序)--> source1 --> source2

define(["dependency1","dependency2","source1","source2"], function() {
 
);

 

转载于:https://www.cnblogs.com/JoannaQ/p/3393530.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值