SoFunction
Updated on 2025-03-04

A brief analysis of modular writing of js

requirejs is a JavaScript file and module loader. requireJS allows you to separate your javascript code into files and modules, while managing dependencies between each module.

RequireJS's goal is to encourage modularity of the code, which uses script loading steps different from the traditional "script" tag. Loading modular scripts with RequireJS will improve the loading speed and quality of your code.

1. Why use it?

At the earliest, all Javascript code was written in one file, and just loading this file was enough. Later, there was more and more code, and one file was not enough, so it had to be divided into multiple files and loaded in turn. I believe many people have seen the following web code:

  <script src=""></script>
<script src=""></script>
<script src=""></script>
<script src=""></script>
<script src=""></script>
<script src=""></script>

This code loads multiple js files in turn.

This writing style has great disadvantages.

  1. First of all, when loading, the browser will stop rendering of the web page. The more files are loaded, the longer the web page will lose response time.
  2. Since there is a dependency between js files, the loading order must be strictly guaranteed (such as the one in front of the above example). The module with the largest dependency must be loaded at the end. When the dependency relationship is very complicated, the code writing and maintenance will become difficult.

The birth of this is to solve these two problems:

  1. Implement asynchronous loading of js files to prevent web pages from losing response;
  2. Manage the dependencies between modules, which facilitates code writing and maintenance.

2. Loading

The first step to use is to download the latest version at the official website.

After downloading, assume that it is placed under the js subdirectory and it can be loaded.

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

Some people may think that loading this file may also cause the web page to lose its response. There are two solutions:

One is to load it at the bottom of the web page, and the other is to write it as follows:

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

The async attribute indicates that this file needs to be loaded asynchronously to prevent the web page from losing response. IE does not support this property, only supports defer, so write defer on it.

After loading, the next step is to load our own code. Assume that our own code file is, and it is also placed under the js directory. Then, just write it as follows:

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

The function of the data-main attribute is to specify the main module of the web program.

In the above example, this file will be loaded first in the js directory. Since the default file suffix name is js, you can abbreviate it as main.

3. How to write the main module

In the previous section, I called it "main module", which means the entry code of the entire web page. It's a bit like the main() function in C language, and all the code starts from here.

Let’s see how to write it.

If our code does not depend on any other modules, then we can write the javascript code directly.

 // 
 alert("Loading successfully!");
But that's the case,There is no need to use it。The real common situation is,The main module depends on other modules,You must use it nowAMDSpecification definedrequire()function。 // 
require(['moduleA', 'moduleB', 'moduleC'], function (moduleA, moduleB, moduleC){
 // some code here
});

The require() function accepts two parameters. The first parameter:

An array represents the module to which it depends. The above example is ['moduleA', 'moduleB', 'moduleC'], that is, the main module depends on these three modules;

A callback function, after all currently specified modules are loaded successfully, it will be called. The loaded module will be passed in the function as a parameter, so that these modules can be used inside the callback function.

require() loads moduleA, moduleB and moduleC asynchronously, and the browser will not lose response; the callback function it specifies will only run after the previous modules are successfully loaded, solving the dependency problem.

Below, let's look at a practical example.

Assuming that the main module depends on three modules: jquery, underscore and backbone, you can write it like this:

 require(['jquery', 'underscore', 'backbone'], function ($, _, Backbone){
    // some code here
});

jQuery, underscore, and backbone will be loaded first, and then the callback function will be run. The code of the main module is written in the callback function.

4. Module loading

In the last example in the previous section, the dependent module of the main module is ['jquery', 'underscore', 'backbone']. By default, assume that these three modules are in the same directory, the file names are, and then automatically loaded.

Using the() method, we can customize the loading behavior of the module. () is written at the head of the main module (). The parameter is an object, and the paths attribute of this object specifies the loading path of each module.

({
 paths: {
 "jquery": "",
 "underscore": "",
 "backbone": ""
 }
});

The above code gives the file names of the three modules, and the path is in the same directory (js subdirectory). If these modules are in other directories, such as the js/lib directory, there are two ways to write them.

One is to specify the path one by one.

({
 baseUrl: "js/lib",
 paths: {"jquery": "", "underscore": "", "backbone": ""}
});

The other is to directly change the base directory (baseUrl).

({
 baseUrl: "js/lib",
 paths: {
  "jquery": "",
  "underscore": "",
  "backbone": ""
 }
});

If a module is on another host, you can also directly specify its URL, such as:

 ({
  paths: {
  "jquery": "/ajax/libs/jquery/1.7.2/"
  }
 });

Require:

Each module is a separate js file. In this way, if multiple modules are loaded, multiple HTTP requests will be issued, which will affect the loading speed of the web page. Therefore, an optimization tool is provided. After the module is deployed, multiple modules can be merged into one file to reduce the number of HTTP requests.

5. How to write AMD module

The loaded module adopts the AMD specification. In other words, the module must be written in accordance with AMD's regulations.

Specifically, the module must be defined using a specific define() function. If a module does not rely on other modules, it can be defined directly in the define() function.

Suppose there is now a file that defines a math module. Then, just write it like this:

  // 
 define(function (){
 var add = function (x,y){
 return x+y;
 };
 return {
 add: add
 };
 });

The loading method is as follows:

  // 
  require(['math'], function (math){
  alert((1,1));
  });

If this module also depends on other modules, the first parameter of the define() function must be an array indicating the dependency of the module.

  define(['myLib'], function(myLib){
 function foo(){
 ();
 }
 return {
 foo : foo
 };
 });

When the require() function loads the above module, the file will be loaded first.

6. Load non-standard modules

Theoretically, the loaded module must be a module defined in accordance with the AMD specification and defined using the define() function. But in fact, although some popular function libraries (such as jQuery) have already complied with AMD specifications, more libraries do not comply with them. So, can non-standard modules be loaded?

The answer is OK.

Before loading such modules with require(), you must first use the () method to define some of their features.

For example, both underscore and backbone libraries are not written in the AMD specification. If they are to be loaded, their characteristics must be defined first.

 ({
  shim: {
   'underscore': {
    exports: '_'
   },
   'backbone': {
    deps: ['underscore', 'jquery'],
    exports: 'Backbone'
   }
  }
 });

() Accepts a configuration object. In addition to the paths attribute mentioned above, this object also has a shim attribute, which is specially used to configure incompatible modules. Specifically, each module needs to define (1) the exports value (the output variable name), indicating the name when the module is called externally; (2) the deps array, indicating the dependence of the module.

For example, jQuery plug-in can be defined like this:

 shim: {
 '': {
 deps: ['jquery'],
 exports: ''
 }
 }

7. Plug-in

A series of plug-ins are also provided to implement some specific functions:

The domready plug-in allows the callback function to be run after the page DOM structure is loaded.

 require(['domready!'], function (doc) {
  // called once the DOM is ready
 });

Text and image plugins allow loading of text and image files.

 define([
    'text!',
    'image!'
   ],
   function (review, cat) {
    (review);
    (cat);
   }
 );

Similar plugins include json and mdown, which are used to load json files and markdown files.

Interested friends can check it out:https:///article/

The above is all the content of this article. I hope the content of this article will be of some help to everyone’s study or work. If you have any questions, you can leave a message to communicate. At the same time, I hope to support me more!