RequireJS Use Summary 1 - for Effective JavaScript Module Loading

1. The difference between require and define the

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

  • require () - statement or module defined once, or a statement or module executed immediately
  • define () - a module that can be reused, can be placed in different places

2. Loading the order management file dependencies --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 using asynchronous modules loaded mechanism (AMD), that is, each individual module is loaded by asynchronous request, that is no guarantee that the first file loaded first before the second file, for this purpose, RequireJS use shim to force order definition file is loaded, as the following code:

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.

As defined above represents: Source2 dependent on source1, only after completion of loading Loading source1 Source2; source1 and depends on dependency1 dependency2, dependency1 only after completion of loading and loading dependency2 source1, so that the whole loading sequence is:

                                                dependency1, dependency2 (not specified loading sequence of the two files) -> Source1 -> Source2

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

 

Reproduced in: https: //www.cnblogs.com/JoannaQ/p/3393530.html

Guess you like

Origin blog.csdn.net/weixin_33860147/article/details/94153760