English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Detailed Explanation of RequireJs

I. Why use RequireJS?

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

When loading multiple js files as mentioned above, the browser will stop rendering the web page (JS blocks the browser rendering),the more files loaded, the longer the time the web page loses response; in addition, it is difficult to manage the dependencies between various files.

The role of RequireJs:

(1)Achieves asynchronous loading of js files, avoiding the web page from losing response;

(2)Manages dependencies between modules, facilitating code writing and maintenance.

(3)Defined a scope to avoid pollution of the global namespace.

2. Loading require.js

1.FromOfficial websiteDownload the latest version of require and place it in the js directory, and use script to include the page:

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

To prevent blocking the page rendering, it can be placed at the bottom of HTML or changed to the following method:

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

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

2.Load page logic code:

Assuming the code file is main.js and it is also placed in the js directory, the following methods can be used to include it:

Method1:

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

data-The main attribute specifies the main entry of the web program, which will be loaded first by requirejs. Since requirejs defaults to depending on resources that are js, main.js can be abbreviated to main.

Method2:

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 be loaded by requirejs to be registered
 require([moduleAName], function (moduelA) {
 //Logic code
 )
});

3. Writing the Main Module

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

The require() function accepts two parameters: the first parameter is an array representing the modules that the current module depends on; the second parameter is a callback function, which will be called after all the specified modules have been successfully loaded. The loaded modules will be passed as parameters to the callback function, so these modules (modules with return values) can be used within the callback function.

require() asynchronously loads moduleA, moduleB, and moduleC, and the browser will not lose its responsiveness; the callback function it specifies will only run after all the dependent modules have been downloaded and executed the corresponding callbacks.

4. Module Configuration

The require.config() method can define module paths and define dependencies in the form of short module names. This methodIt can be written before each main module (main.js) and used in conjunction with the main module.

The parameter is an object, which specifies the loading paths of various modules through the paths attribute of the object.Multiple paths can be configuredIf the remote CDN library does not load successfully, load the local library.

If the module configuration is not defined, the dependencies in the main module need to be written with the full path.

Configure paths on each page as needed:

require.config({  //module registration configuration, for use by subsequent 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 the config as a separate js file, then

require([“configJsUrl”],function(){  //It is necessary to load the module configuration asynchronously through require in the main file
 require([‘ModuleName’],function(Name){
 …other code
 )
)

To avoid nesting require in each page, you can also use the following method:

First create a separate config.js file:

require.config({ //module registration configuration, for use by subsequent 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": "path relative to baseUrl, omit the module file suffix .js"
 },
 // libraries written in non-AMD mode need to be reconfigured
 shim: {
 underscore: {
  exports:'_'
 },
 backbone (short module name still needs to define the path): {
  exports: 'Backbone',      //library output variable name indicates the name when this module is called externally
  deps:['jquery','underscore'] //dependencies of this module
 }
 },
 urlArgs: "bust=" + document.getElementById('publishDate').attributes['value'].value  //js resource parameters control version refresh cache
});
define([ 'marionette'], function () { }); //仍是会被执行的js代码,会依次加载需要的模块

然后通过如下方式使用:

通过主入口直接将模块配置注册到requirejs命名空间中,页面中后续的require方法无需再注册,可以直接使用短模块名进行依赖加载。

如果没有显式指定config及data-main,则默认的baseUrl为加载RequireJS的HTML页面所在目录。如果指定了data-main而没有在config中指定根路径,则该路径被设为baseUrl。

若想避开"baseUrl + paths"的解析过程,而是直接指定加载某一个目录下的脚本。可以这样做:如果一个module ID符合下述规则之一,其ID解析会避开常规的"baseUrl + paths"配置,而是直接将其加载为一个相对于当前HTML文档路径的脚本:

•    以 ".js" 结束.

•    以 "/" 开始.

•    包含 URL 协议, 如 "http:" or "https:".

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

require.js要求,每个模块是一个单独的js文件。加载多个模块就会发出多次HTTP请求,影响网页的加载速度。因此require.js提供了一个优化工具(r.js),当模块部署完毕以后,可以用这个工具将多个模块合并在一个文件中,减少HTTP请求数,但又需要和缓存之间进行取舍。

六、AMD模块的写法

require.js加载的模块,必须按照AMD的规定来写。即模块必须采用特定的define()函数来定义,通常返回一个对象,该对象具有供别的模块使用的方法或属性;或只执行相关逻辑而无输出。

七、require.js的相关插件

text插件,允许require.js异步加载txt、css或html等文本资源供js使用,而不需要在script内构建Html字符串。

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 through [] or through the require() method in the callback function, with the same effect. Because the define method will scan the dependencies of require methods in the callback function with regular expressions first and download them, and then execute the callback function. But at this time, it is necessary to pass in the dependency require itself, otherwise an error will occur:

define(function(require) {
 var helper = require('helpModuleUrI');//It will also load the dependency in advance
 ...
)

When multiple modules depend on the same module in turn multiple times, the module will only be downloaded and initialized once, and then require will keep its reference for other modules to use again.

Distinguish the execution of require methods and the execution of callbacks:

require('config', callBack1);
require('b', callBack2);
// The two require methods will be executed immediately, but the execution order of callBack is uncertain and depends on the download order.
//Different from the following code, it will execute strictly in order
require('config', function() {
 require('b', callBack2)
)

That's all for the content of this article. I hope the content of this article can bring a certain amount of help to everyone's learning or work, and I also hope to get more support for the Yelling Tutorial!

Declaration: The content of this article is from the Internet, the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (when sending an email, please replace # with @ to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the infringing content involved.)