Detailed Explanation of the Use of RequireJs

  • 2021-07-22 08:23:39
  • OfStack

1. Why use RequireJS?


    <script src="a.js"></script>
        <script src="b.js"></script>
        <script src="c.js"></script>

When the above-mentioned js files are loaded, the browser will stop rendering the web page (JS blocks the browser rendering), and the more files are loaded, the longer the time for the web page to lose response will be; In addition, the dependencies of various files are difficult to manage.

Role of RequireJs:

(1) Realize the asynchronous loading of js file to avoid the web page losing response;

(2) Manage the dependencies between modules, which is convenient for code writing and maintenance.

(3) A scope is defined to avoid global namespace pollution.

2. Loading of require. js

1. Download the latest version of require from official website, put it in the js directory, and use script to introduce the page:

<script src="js/require.js"></script>

In order not to block page rendering, you can put it at the bottom of HTML or change it to the following way:

<script src="js/require.js" defer async="true" ></script>

The async attribute indicates that the file needs to be loaded asynchronously (defer attribute is compatible with IE).

2. Load the page logic code:

Assuming that the code file is main. js, also in the js directory, it is introduced in the following ways:

Mode 1:

<script  data-main="js/main" src="js/require.js"></script>

The data-main attribute specifies the main entry of the Web page program, which will be loaded first by requirejs. requirejs depends on js by default, so main. js can be abbreviated to main.

Mode 2:

After loading require. js, load the config configuration file (if any) through requirejs, and finally load the main module:


require([ ' configUrl'],function () { //config.js Must pass requirejs Load to register 
 require([moduleAName],function(moduelA){
 // Logic code 
 })
});

3. How to write the main module


// main.js
    require(['moduleA', 'moduleB', 'moduleC'], function (moduleA, moduleB, moduleC){
          // some code here
    });

The require () function takes two arguments, the first of which is an array representing the modules on which the current module depends; The second argument is a callback function, which will be called after all the modules specified above have been successfully loaded. Loaded modules are passed into the callback function as parameters so that they can be used inside the callback function (dependent modules have return values).

require () loads moduleA, moduleB, and moduleC asynchronously without the browser losing its response; It specifies a callback function that will not run until all the modules currently dependent on are downloaded and the corresponding callbacks are executed.

4. Module configuration

The require. config () method defines the path of a module and defines dependencies in the form of short module names. This method can be written in front of each main module (main. js) and used in conjunction with main module 1.

The parameter is an object whose paths property specifies the loading path of each module. paths can configure multiple paths, and if the remote cdn library does not load successfully, the local library is loaded.

If the configuration of the module is not defined, the dependency in the main module needs to write the full path.

Configure the path on demand on each page:


require.config({  // Register the configuration of the module for later code 
          baseUrl: '/js/', 
 paths: {
     "jquery": " cdnUrl " , "Jquery/jquery-1.12.0.min"
  "fixheight": "login/fixheight"
 }
 });
 require(['jquery', 'fixheight'], function ($, fixHeight) {
 ...other code; 
 fixHeight.init();
});

Or configure config as a separate js file, and then


require([ " configJsUrl " ],function(){  // Need to be in main File through require Load module configuration asynchronously first 
 require([ ' ModuleName'],function(Name){
  … other code
 })
})

To avoid nesting require on every page, you can also do the following:

Create a separate config. js file first:


require.config({ // Register the configuration of the module for later code 
 baseUrl: "/js/app/", // Other dependencies are relative paths to this location 
 //  Path configuration 
 paths: {
underscore: 'vender/underscore.min',   backbone:'vender/backbone.min'
 jquery:  ' cdnUrl','vender/jquery/jquery-1.12.0.min',
  "Module short name" : "Relative to baseUrl The path address of, omitting the suffix of the module file .js " 
 },
 //  Non AMD Class libraries written by patterns need to be reconfigured 
 shim: {
 underscore: {
  exports:'_'
 },
 backbone (Short module name still needs to define path) : {
  exports: 'Backbone',            // The variable name output by the class library indicates the name of this module when it is called externally 
  deps:['jquery','underscore'] // Dependencies of this module 
 }
 },
 urlArgs: "bust=" + document.getElementById('publishDate').attributes['value'].value    //js Parameters of the resource, which controls the version refresh cache 
});
define([ 'marionette'], function () { }); // It will still be executed js Code, which will load the required modules in turn 

Then use it in the following ways:

<script data-main="js/config" src="js/require.js"></script>

The module configuration is directly registered in the requirejs namespace through the main entry, and the subsequent require methods in the page do not need to be registered again, and can directly use the short module name for dependency loading.

If config and data-main are not explicitly specified, the default baseUrl is the directory where the RequireJS page is loaded. If data-main is specified and the root path is not specified in config, the path is set to baseUrl.

If you want to avoid the parsing process of "baseUrl + paths", you should directly specify to load scripts in a certain directory. You can do this: If an module ID complies with one of the following rules, its ID parsing avoids the regular "baseUrl + paths" configuration and loads it directly as a script relative to the current HTML document path:

End with ". js".

Start with "/".

Includes URL protocols, such as "http:" or "https:".

eg. require(['/www/js/app/vender/underscore.min.js'], function (_) {…})

require. js requires that each module be a separate js file. Loading multiple modules will send out multiple HTTP requests, which will affect the loading speed of web pages. Therefore, require. js provides an optimization tool (r. js). After the module is deployed, it can be used to merge multiple modules into one file to reduce the number of HTTP requests, but it needs to choose between cache and cache.

6. AMD Module Writing

require. Modules loaded by js must be written in accordance with AMD. That is, the module must be defined with a specific define () function, which usually returns an object with methods or properties for other modules; Or just execute related logic without output.

7. require. Related plug-ins for js

The text plug-in allows require. js to asynchronously load text resources such as txt, css, or html for use by js without the need to build Html strings within script.


define(['text!components/multiple/template.html', 'image!cat.jpg'],
 function(template,cat){
 $('body').append($(template));
 document.body.appendChild(cat);
   }
); 

Note:

Module dependencies can be introduced either through [] or through the require () method in the callback function, with 1 effect. Because the define method scans the dependencies of the require method in the callback function through regularization and downloads them before executing the callback function. But at this time, you need to pass in the dependency require itself, otherwise an error will be reported:


define(function(require){
 var helper=require( ' helpModuleUrI');// The dependency is also loaded in advance 
  … 
})

When multiple modules depend on the same module several times, the module is downloaded and initialized only once, after which require keeps a reference to it for reuse by other modules.

Distinguish between require method execution and callback execution:


require('config',callBack1);
require('b',callBack2);
//  Two require Method executes immediately, but callBack The order of execution of is uncertain, depending on the order of download. 
// Unlike the following code, it will be executed in strict order 
require('config',function(){
 require('b',callBack2)
})

Related articles: