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() { );