Javascript Modular Programming (III): Usage of require.js

Of this series Part I and Part II , introduced the Javascript module prototype and theoretical concepts, and today we will introduce how to use them in practice.

I use a very popular library require.js

1、 Why use require.js?

In the earliest days, all the Javascript code was written in a file. It was enough to load this file. Later, there were more and more codes. 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="1.js"></script>
  <script src="2.js"></script>
  <script src="3.js"></script>
  <script src="4.js"></script>
  <script src="5.js"></script>
  <script src="6.js"></script>

This code loads multiple js files in turn.

This writing has great shortcomings. First, when loading, the browser will stop rendering the web page. The more files loaded, the longer the web page will lose response; Secondly, because there are dependencies between js files, the loading order must be strictly guaranteed (for example, 1. js in the above example must be in front of 2. js). The module with the greatest dependency must be loaded last. When the dependencies are very complex, code writing and maintenance will become difficult.

Require.js was born to solve these two problems:

  

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

(2) Manage dependencies between modules to facilitate code writing and maintenance.

2、 Loading of require.js

The first step to use require.js is to go to the official website first download Latest version.

After downloading, suppose you put it under the js subdirectory, and you can load it.

  <script src="js/require.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 page, and the other is to write as follows:

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

The async attribute indicates that the file needs to be loaded asynchronously to avoid the Web page losing response. IE does not support this attribute and only supports defer, so defer is also written.

After loading require.js, the next step is to load our own code. Suppose our own code file is main.js, which is also placed under the js directory. Then, just write as follows:

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

The data main attribute is used to specify the main module of the webpage program. In the above example, it is main.js under the js directory. This file will be the first to be loaded by require.js. Since the default file suffix of require.js is js, you can abbreviate main.js to main.

3、 Writing of main module

The main.js in the previous section is called the "main module", which means the entry code of the entire web page. It is a bit like the main () function of C language, and all the code runs from here.

Let's see how to write main.js.

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

  // main.js

Alert ("Loading succeeded!");

However, in this case, it is unnecessary to use require.js. It is really common that the main module depends on other modules, so the require() function defined in the AMD specification should be used.

  // main.js

  require(['moduleA', 'moduleB', 'moduleC'], function (moduleA, moduleB, moduleC){

    // some code here

  });

The require() function takes two arguments. The first parameter is an array, which represents the module it depends on. The example above is ['moduleA ',' moduleB ',' moduleC '], that is, the main module depends on these three modules; The second parameter is a callback function, which will be called when the previously specified modules are successfully loaded. The loaded modules will be passed into the function in the form of parameters, 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 specified by it will run only after the previous modules are loaded successfully, which solves the dependency problem.

Next, let's look at a practical example.

Assuming that the main module depends on three modules: jquery, underscore, and backbone, main.js can write as follows:

  require(['jquery', 'underscore', 'backbone'], function ($, _, Backbone){

    // some code here

  });

Require.js will first load jQuery, underscore and backbone, and then run the callback function. 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 modules of the main module are ['jquery ',' underscore ',' backbone ']. By default, require.js assumes that these three modules are in the same directory as main.js, and the file names are jquery.js, underscore.js, and backbone.js, and then they are automatically loaded.

Using the require. config () method, we can customize the loading behavior of the module. Require.config() is written at the head of the main module (main. js). A parameter is an object whose path attribute specifies the loading path of each module.

  require.config({

    paths: {

      "jquery": "jquery.min",
      "underscore": "underscore.min",
      "backbone": "backbone.min"

    }

  });

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

  require.config({

    paths: {

      "jquery": " lib/ jquery.min",
      "underscore": " lib/ underscore.min",
      "backbone": " lib/ backbone.min"

    }

  });

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

  require.config({

     baseUrl: "js/lib",

    paths: {

      "jquery": "jquery.min",
      "underscore": "underscore.min",
      "backbone": "backbone.min"

    }

  });

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

  require.config({

    paths: {

      "jquery": " https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min "

    }

  });

Require.js requires that each module is a separate js file. In this way, if multiple modules are loaded, multiple HTTP requests will be sent, which will affect the loading speed of the web page. Therefore, require.js provides a Optimization tools After the module is deployed, you can use this tool to combine multiple modules into one file to reduce the number of HTTP requests.

5、 Writing of AMD module

The module loaded by require.js adopts AMD specification. In other words, modules must be written according to AMD regulations.

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

Suppose you now have a math. js file that defines a math module. Math.js will write as follows:

  // math.js

  define(function (){

    var add = function (x,y){

      return x+y;

    };

    return {

      add: add
    };

  });

The loading method is as follows:

  // main.js

  require(['math'], function (math){

    alert(math.add(1,1));

  });

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

  define(['myLib'], function(myLib){

    function foo(){

      myLib.doSomething();

    }

    return {

      foo : foo

    };

  });

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

6、 Load non-standard modules

Theoretically, the module loaded by require.js must be defined with the define() function according to the AMD specification. However, in fact, although some popular function libraries (such as jQuery) already conform to the AMD specification, more libraries do not. Can require.js load non-standard modules?

The answer is yes.

Before such modules are loaded with require(), they need to use the require.config() method to define some of their characteristics.

For example, both the underscore and backbone libraries are not written in accordance with the AMD specification. If you want to load them, you must first define their characteristics.

  require.config({

    shim: {

      'underscore':{
        exports: '_'
      },

      'backbone': {
        deps: ['underscore', 'jquery'],
        exports: 'Backbone'
      }

    }

  });

Require.config() accepts a configuration object. In addition to the path attribute mentioned above, this object also has a shim attribute, which is used to configure incompatible modules. Specifically, each module should define (1) the exports value (the name of the output variable), indicating the name of the external call of the module; (2) Deps array, indicating the dependency of the module.

For example, jQuery plug-ins can be defined as follows:

  shim: {

    'jquery.scroll': {

      deps: ['jquery'],

      exports: 'jQuery.fn.scroll'

    }

  }

7、 Require.js plug-in

Require.js also provides a series of plug-in unit To implement some specific functions.

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

  require(['domready!'], function (doc){

    // called once the DOM is ready

  });

The text and image plug-ins allow require.js to load text and image files.

  define([

    'text! review.txt',

    'image! cat.jpg'

    ],

    function(review,cat){

      console.log(review);

      document.body.appendChild(cat);

    }

  );

Similar plug-ins include json and mdown, which are used to load json files and markdown files.

(End)

Message (129)

Backbone does not rely on jQuery. Why write deps: ['underscore ',' jquery ']?

How should I use exports: 'Backbone'?

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

Look at these three Javascript articles introduced by your blog, and I'm going to try!

@Zi Bu Yu

The official website reads:

Backbone's only hard dependency is Underscore.js ( > 1.3.1). For RESTful persistence, history support via Backbone. Router and DOM manipulation with Backbone. View, include json2.js, and either jQuery ( > 1.4.2) or Zepto.

@Zibuyu:

The former is correct.

Next time, introduce seajs and cmd

It is not convenient to debug with this, and can not solve the debugging problem

I heard that Google unblocked today. I tried it. It's really fast. I haven't used Google for a long time.

I wrote about SeaJS http://cyj.me/why-seajs/zh/ , also translated Two articles about technical ideas on the RequireJS website http://cyj.me/why-seajs/requirejs/

Habit seajs

 To quote from abian:

I heard that Google unblocked today. I tried it. It's really fast. I haven't used Google for a long time.

You can use the Chrome browser+Prefer HTTPS plug-in. When you open Google and Google search results, you use the HTTPS protocol, and the seal is broken successfully!

Ruan wrote these three articles very well! Get rid of my doubts about this! Top!!
In addition, I transferred these three articles. ha-ha


  require.config({

    paths: {

      "jquery": "jquery.min.js",
      "underscore": "underscore.min.js",
      "backbone": "backbone.min.js"

    }

  });

You should not add. js, or the example will fail.

 Quote Arthur's speech:

You should not add. js, or the example will fail.

Thank you for pointing out. This code was written by hand. It was not verified on the computer at that time. It was really wrong and has been corrected.

Seems like

require.config({...})

should be:

requirejs.config({...}) ?

Ruan has time to write an article on backbone.js. This is very fluent recently, but the documents on the official website are really poor. I can't understand them.

What you see when you view the document:
There may be times when you do want to reference a script directly and not conform to the "baseUrl + paths" rules for finding it. If a module ID has one of the following characterstics, the ID will not be passed through the "baseUrl + paths" configuration, and just be treated like a regular URL that is relative to the document:
*Ends in ".js".
*Starts with a "/".
*Contains an URL protocol, like "http:" or "https:".

It means that I don't understand. In the main file, I write all the modules to be used?
For example, if there is a page A that only needs the math module, and a page B that only needs the add module, both of which are written in the main file, then both pages A and B are loaded with two modules at the same time.

Thanks for sharing. Looking forward to more articles related to Backbone. Can you make friendship links?

 Quote Andy's speech:

It means that I don't understand. In the main file, I write all the modules to be used?
For example, if there is a page A that only needs the math module, and a page B that only needs the add module, both of which are written in the main file, then both pages A and B are loaded with two modules at the same time.

Both page A and page B can write their own main modules

Let me ask you how to load backbone.localStorage.js? require(['jquery','underscore','backbone','?'],function($,_,Backbone,?){}

Very good, written well!

I package js in dojo and generate files
require({cache:{"custom/MyModule":function () {
define(["dojo/_base/lang"], function (lang) {
......
})
}
},
......
This require() looks like a map. How can I call the methods in the module when I load the module

It's very rewarding! thank you.

You have benefited a lot, like! How to reasonably organize the code when using a framework such as extjs in a project

RequireJS and Backbone, which have been used for a long time, have not been systematically studied because they are half baked Today, I understood the difference between AMD and CommonJS for the first time, and then I understood the principle of RquireJS thank you

Praise me and appreciate the Internet thinking of God.

After reading many of your articles on javascript, I have benefited a lot. I think requirejs also has the advantage of managing global variables and namespaces. Although many frameworks can be implemented, or you can package the front-end framework yourself, it is always much more convenient to use requirejs.

It seems that the API has been in the clouds for a long time, but the Chinese documents are true.

Teacher, I just got to know Ozjs, but I didn't find much information about Ozjs! Is the purpose of requirejs and ozjs the same

There is a question about requirejs: there are three pages A, B and C, and these three pages have a common module common.js. Common.js depends on suggestion.js, taset.js, localStorage.js. Then on page A, you need an a.js, which depends on localStorage.js. Because the content of common changes frequently, it is placed in the page as a separate js. Now the problem arises. How can we load two main modules of requirejs in the page at the same time? Both modules use localStorage.js. How can we avoid repeated loading (referring to the compression and consolidation of code in advance when offline)

How to use the methods in the module on the page, for example, how to add onclick directly here without bind

I really appreciate the blogger. Recently, require.js happened to be used in the project. I was dazzled when I saw this one, two and three movies.

Excuse me, downstairs owner, how to control the requirejs version management? Version No

There is a problem. If a main.js depends on aa, bb, cc...... N small modules, when the nth module is executed, the method is undefined,
For example, the cc. add() method called prompts that there is no add method

 Quote the speech of oneway:

Seems like

require.config({...})

should be:

requirejs.config({...}) ?

Yes, it should be requirejs. config ({...})

Usually, we use bootjs + headjs + requerjs to load our models. :)

Thank you very much. Your blog is easy to understand, easy to understand, and can explain a problem thoroughly. It's really very good, thank you!

Hola, please ask me a question. When using require, how to write a unified portal for the entire website? I am now in this situation. Instead of using data main to write the entry, I write my own requirements in each page (as shown below). However, it seems that data main is not used. Grunt requirejs cannot package the loaded modules together, but because the modules required by each page are different, I do not know how to write a unified entry, Please give me some advice

<!-- build:js scripts/require.js -->
<script src="bower_components/requirejs/require.js"></script>
<!-- endbuild -->
<script>
require(['scripts/config'], function() {
require(['scripts/album/create']);
});
</script>

I think it's boring. Even if I load five js files, I can also write an asynchronous loading method myself. All of the requirejs are very large. With the jquery file and my own js, how big is it

 To quote Jeremy's statement:

I think it's boring. Even if I load five js files, I can also write an asynchronous loading method myself. All of the requirejs are very large. With the jquery file and my own js, how big is it

Yes, it is, so it is all typed into a file in the end

These are used for small projects. They are ostentatious and have a sense of forced decoration. Large projects are very useful.

Isn't Shim dependent on settings? There are also examples of not writing exports on the official website
requirejs.config({
shim: {
'jquery.colorize': ['jquery'],
'jquery.scroll': ['jquery'],
'backbone.layoutmanager': ['backbone']
}
});

I benefited a lot from reading Mr. Ruan's article. Thank you.

 Quote Zibuyu's speech:

Backbone does not rely on jQuery. Why write deps: ['underscore ',' jquery ']?

How should I use exports: 'Backbone'?

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

My own test results are useless. Originally, other libraries just add one in the global variable. For example, jQuery will add window. $, If require.js has loaded jQurey, then the $of the global variable should be jQuery, and you can use $directly

The simplest and rudest introduction to requirejs.
Bangbang.

If you only control the loading order, it is not enough to write in order on the jsp page. Why do you need require.js???

 Quote Bo's speech:

If you only control the loading order, it is not enough to write in order on the jsp page. Why do you need require.js???

Because the dependency cannot be controlled when it is written in the jsp.

 Quote Bo's speech:

If you only control the loading order, it is not enough to write in order on the jsp page. Why do you need require.js???

You must have never written js

If I configure the global public file
require.config({
baseUrl: 'js',
paths: {
a: 'a',
b: 'b',
c: 'c'
}
});
There is a separate file that needs to be added to a separate configuration
require.config({
baseUrl: 'js',
paths: {
d: 'd'
}
});
Is it overwritten like this, or is there any method to add to config.pathss?

Easy to understand!!!

That's great!

I am tired of writing JS repeated code and want to try modular development. Then I am bewildered by various new technologies and terms. I came here to read many articles in succession. I really benefited a lot. I explained the original profound things very simply and easily, which was very helpful for the initial understanding and also eliminated some original fears. Thank you very much!!!

Very good, definitely benefited

Much better than the official documents

 Quote igody's statement:

Yes, it should be requirejs. config ({...})

Test requier.config ({
//doing something
}) via

I used to read articles almost without comment, but this time I must stand up. The teacher wrote really well.

Let me ask you a question:
I configured jquery in main.js as follows:
require.config({
baseUrl: '/js/',
paths: {
'jquery': 'lib/jquery/jquery-1.7.1.min'
}
});

My intention is to define the path of some public js (jquery, cookie, etc.), and then call the alias directly in other js instead of writing the full path. As follows:


require(['jquery'], function($){
$('body').html('test');
}); a

However, this cannot be achieved. It can only be called in main.js. I want to ask whether there is a way to implement such a call? thank you!

 To quote Jeremy's statement:

I think it's boring. Even if I load five js files, I can also write an asynchronous loading method myself. All of the requirejs are very large. With the jquery file and my own js, how big is it

Not only for asynchrony, but also for modular programming For example, A.js B.js, where B.js needs to use the parameters passed from A.js

At the end of the reading,
"The text and image plug-ins allow require.js to load text and image files." Is the code below incorrect?

`Define 'may be' require`

```javascript
  define([
    'text! review.txt',
    'image! cat.jpg'
    ],

    function(review,cat){
      console.log(review);
      document.body.appendChild(cat);
    }
  );
```

And the Gradle on Android

 To quote zcz's statement:

If I configure the global public file
require.config({
baseUrl: 'js',
paths: {
a: 'a',
b: 'b',
c: 'c'
}
});
There is a separate file that needs to be added to a separate configuration
require.config({
baseUrl: 'js',
paths: {
d: 'd'
}
});
Is it overwritten like this, or is there any method to add to config.pathss?

It doesn't matter if it's written directly in the overall situation. D will be loaded only when define (['d '], function() {}) is written when it is used. This is defined globally to reduce the number of paths used. If the path of jquery is not defined, then every reference to jquery must be written as follows: define(['lib/jquery.min'],function($){})

If paths are defined:
require.config({
paths: {
jquery: 'lib/jquery.min'
}
});

Then every reference to jquery can be written as follows:
define(['jquery'],function($){})

 To quote Jeremy's statement:

I think it's boring. Even if I load five js files, I can also write an asynchronous loading method myself. All of the requirejs are very large. With the jquery file and my own js, how big is it

Our current project index.html contains more than 300 js files, which is in urgent need of requirejs to remove dependencies.

Thank you for your good article

After so many years, if you don't update, you can still afford the bitter youth~~>

Blogger, your About Me, the last line should change watching movies to watching movies. If I hadn't learned your requirejs, I would have told you?!

I have been using requirejs all the time, but it was not built by me, but by Daniel. It is very helpful to read this article, and I will also like it

Teacher, this is what we use for development, but recently we encountered the problem of repeated loading. The framework highcharts.js was called in a js file, and the js file should be referenced in both the pre login and post login pages, so that users can enter the post login page from the pre login page, and the problem of repeated loading will occur. How to solve this problem, I hope the teacher can answer this question. Thank you

The Javascript article is really good. I learned

 To quote hhq's statement:

Test requier.config ({
//doing something
}) via

In fact, requier===requierjs

 To quote forevermnj's statement:

Teacher, this is what we use for development, but recently we encountered the problem of repeated loading. The framework highcharts.js was called in a js file, and the js file should be referenced in both the pre login and post login pages, so that users can enter the post login page from the pre login page, and the problem of repeated loading will occur. How to solve this problem, I hope the teacher can answer this question. Thank you

Although the request is repeated, if the page does not jump, the browser should directly use the cache. If there is a jump, different pages are not called repeated loading

The explanation was very good. I learned. Thank you

Brother Feng: I want to ask you a question. If you write in strict accordance with the AMD specification, how should you manage the definition (["m1", "m2"], callback) in the module, where m1 and m2 have dependencies? My test shows that the two orders can be changed at will? Do you want to write casually? It manages dependencies by itself??

 Quote Bo's speech:

If you only control the loading order, it is not enough to write in order on the jsp page. Why do you need require.js???

Require. js is loaded asynchronously.

IE10 supports the async attribute

Can I call the methods defined in the module in the page?

Miss Ruan has been my first teacher. As soon as I have new knowledge to learn, I will go here to learn

If I have multiple pages and call different functions, are they all written on the main file entry, such as a home page, a list page, a detail page, or all the main files loaded!

I have been looking for this document for a long time. Thank you, Ruan Dashen

Teacher Ruan's article is really easy to understand, but there is a problem that errors will be reported under IE7. I checked that it is a problem with the data main attribute, but I still reported errors directly on the home page through require.config (['config.js path '], function() {alert ('callback')}). The company's projects must be compatible with IE7. I don't know why. I checked a lot of data, but I didn't find anyone who said they were incompatible with IE7

 Quote from ericyin:

Teacher Ruan's article is really easy to understand, but there is a problem that errors will be reported under IE7. I checked that it is a problem with the data main attribute, but I still reported errors directly on the home page through require.config (['config.js path '], function() {alert ('callback')}). The company's projects must be compatible with IE7. I don't know why. I checked a lot of data, but I didn't find anyone who said they were incompatible with IE7

I made a small demo and found that an error was reported under ie8: the object does not support this property or method

Learn! Come and review again! Teacher Ruan's articles are all dry goods! Great~

Good benefit

 Quote from Jooos:

If I have multiple pages and call different functions, are they all written on the main file entry, such as a home page, a list page, a detail page, or all the main files loaded!

Dude, have you solved it? I also have this question.

If module A depends on module C and module B also depends on module C, will module C be loaded twice after using requirejs for modular loading?

 To quote xiaowei's statement:

Dude, have you solved it? I also have this question.

You can have a separate entry main file for each page, such as index.js content.js lis.js

Thanks for Ruan's explanation! In simple terms, it's really good!

It has been several years since I read Ruan's article. One small suggestion is that I can browse under the page?

What if you need other js files in addition to the main.js module in a page? This js works independently. Do you want to load this js separately?

It's a bit of a hole. I've used up all of them and developed them. Only then did I know that ie is incompatible!!!! "The object does not support this property or method" appears when jQuery is loaded under ie. It is the same in N versions of jQuery

 Quote cyper's statement:


Our current project index.html contains more than 300 js files, which is in urgent need of requirejs to remove dependencies.

With more than 300 JS, I feel proud of what you said. I can only say that your development management is chaotic enough, and one file and one method does not need more than 300 methods.

Hello, teacher, I have a question for you:

My moduleA depends on jquery. The main.js main file depends on jquery and moduleA. When I write moduleA, does it no longer need to introduce jquery? As long as my main.js introduces jquery

After a try, there is a problem that cannot be solved:
require.js:168 Uncaught Error: Script error for "../jquery.validate", needed by: messages_zh
http://requirejs.org/docs/errors.html#scripterror

Yes, the analysis is very clear, hee hee....

Thank you very much. I see it clearly.

Hello, teacher. I want to ask you how to use requirejs to introduce zepto. Other modules, such as ajax, can be used normally, but the touch module cannot be used normally.

A quick start to a new technical point is more direct by reading Ruan Yifeng's blog...

Let me extract the record in my blog, OK Dada

It suddenly dawned on me!, Thank you, God!

Thank God for his good article

/*global define*/
define([
'jquery',
'underscore',
'backbone',
'collections/todos',
'views/todos',
'text! templates/stats.html',
'common'
],
...

This text! What does it mean

@Yan Jun:

Hello, write this purpose
define.config({
paths: 'lib/jquery-1.9.1.min'
})
Is it just to configure the following path? It is convenient to only write the module name when defining in the future. Is that right?
Can the module on which the define definition depends be understood as a local module? Load only when needed
Requirejs (['sys', 'utils',' ajax '], function (sys, utils, ajax) {}
Is the main module of the page, which is loaded when the file is run

Defer and async have different functions. From the name, defer should load and execute the script after the document is loaded. Async loads and executes asynchronously, and does not block the execution of documents under the script.

 To quote Dante:

If module A depends on module C and module B also depends on module C, will module C be loaded twice after using requirejs for modular loading?

It should not be. After loading, it becomes an object in memory?, If it is judged that the required object already exists in memory, it should be called directly instead of being loaded again. In addition, I think the dependency order of these files specified in the main should be judged during the loading process, and the algorithm should be used to divide the files into several layers. The lowest layer does not need to rely on the js of other modules to load first, so as to ensure the smooth loading of other modules.

It is suggested that there should be a go to top at the end of the article, otherwise, the next chapter should be crossed to the end, and there should be some snacks

The writing was very detailed and the explanations were up to standard. I only used good articles before, but I didn't understand the principles of writing very much. I understand them today

There are two questions that have been unclear:
1: Ruan said that the birth of require.js mainly solved two problems. The first is to realize the asynchronous loading of js files to avoid the browser losing its response, but it can also avoid the browser losing its response without using require.js. For example, if you put the js file at the end or use defer attribute, why do you have to use require?
2: Ruan said that the birth of require.js mainly solved two problems, and the second one was the dependency between management modules. I agree with this, but I don't understand one sentence, as follows (the original text above):

The require() function takes two arguments. The first parameter is an array, which represents the module it depends on. The example above is ['moduleA ',' moduleB ',' moduleC '], that is, the main module depends on these three modules; The second parameter is a callback function, which will be called when the previously specified modules are successfully loaded. The loaded modules will be passed into the function in the form of parameters, so that these modules can be used inside the callback function.

Note the above sentence: The second parameter is a callback function, which will be called when the previously specified modules are successfully loaded.

When all the specified modules are loaded, the callback function will be called, which means that as long as one module is not loaded completely, the callback function will not be called. Does that mean? It will still block the execution of other modules, because it will wait for the module to be loaded. Please help me analyze it. I don't understand


I have a question for your advice:
Let me give a small example. The index.html main.js (main module) lib folder has three sibling relationships in the root directory, jquery-1.12.1. js, underscore. js
Backbone.js is in the lib folder.
require.config({
paths:{
'jquery':'lib/jquery-1.12.1'
},
shim:{
'lib/underscore':{
exports:'underscore'
},
'lib/backbone':{
exports:'backbone',
deps:['lib/underscore','lib/jquery']
}
}
});

Is the Shim attribute written correctly? Should the dependent modules in the array corresponding to deps be written as' lib/underscore 'or' underscore '?

@The cowboy is busy:

1. In addition to the synchronous and asynchronous problems, it is mainly to solve the scope problem, avoid global pollution, and implement modular development
2. The asynchronous callback here does not affect the loading of other modules, but only the current module progress. There are multiple requirements (['fn '], function (fn) {//some code}).

 Quote Bo's speech:

If you only control the loading order, it is not enough to write in order on the jsp page. Why do you need require.js???

More importantly, load on demand

It seems that he has returned to Ruan Da's embrace, which is easy to understand, and the comments are also wonderful. He has gained a lot from beginning to end. Thank you

Brother Ruan Yifeng, I really think your writing is very good, but there is a flaw. The latest version of require.js only supports amd writing, so (If you are wrong, please point out)

Can't the path setting of the js file in config have a suffix? Why? I wrote a suffix and reported an error. It's normal if I don't write a suffix

After reading your article, I used it in my own project. Thank you very much

 Quote You Yuan's speech:

Can't the path setting of the js file in config have a suffix? Why? I wrote a suffix and reported an error. It's normal if I don't write a suffix

The js suffix is added by default, so the. js suffix is not required

Nearly five years.. Mr. Ruan's technology is too advanced. I'm just beginning to understand....

Do you also need to write modules in the required order? Do you want to write them in the dependent order?

How can moduleA, moduleB and moduleC implement asynchronous loading? To understand the loading principle, this is an introduction to the usage, what it solves, and how to solve it

I'm ready to try it!!! Today, I just saw the js teacher Ruan's writing is very easy to understand!!!

Mr. Ruan, can you write an introductory tutorial on vue.js or some troubleshooting? I have been learning vue.js recently, but the foundation is not very good. I feel that vue.js is not as simple as everyone says! I hope Mr. Ruan can pay attention! thank you!

 Quote from Bruce:

Brother Feng: I want to ask you a question. If you write in strict accordance with the AMD specification, how should you manage the definition (["m1", "m2"], callback) in the module, where m1 and m2 have dependencies? My test shows that the two orders can be changed at will? Do you want to write casually? It manages dependencies by itself??

If there is a dependency between m1 and m2, the main. js in m1 or m2 should have written the dependency

The js files are loaded. There is a login dialog layer on the main page, but my login js is loaded, but it doesn't work. How can I solve this problem

The higher is the teacher. Thank Ruan for sharing.

I have read several of your articles on modularity, and I have a question to ask. In the AMD module definition, if the module name (id) is customized, such as define ("testmodule", ["require", "exports", "module"], function (require, exports, module) {....}), then how to correctly reference (require) this module

How can I resolve the conflict between the define variable name in requirejs and the define variable name in jq. 2.2.4

This is the official sample project of requirejs example-multipage All codes in common.js
requirejs.config({
baseUrl: 'js/lib',
paths: {
app: '../ app'
}
});
My question is, can the value of app in the path be a folder instead of a js file?

I have read both sides, but I haven't verified it yet
I have not understood the difference between commonJS and AMD for a long time
keep doning...

Data main="js/main" Is there a clerical error? It should be data main="main. js".

 Quote Mike's speech:

Data main="js/main" Is there a clerical error? It should be data main="main. js".

Don't be so persistent. This is the path. It's OK to put it in the js directory

requirejs.config({
config: {
i18n: {
Locale: 'en'//Configure Chinese and English information
}
})
For the i18n multilingual plug-in in the plug-in, set the locale of i18n under config to 'en',
How can I dynamically modify the locale? For example, I click the Chinese switch button to switch the locale to 'zh',
How to do it?

I want to express my opinion

« - Required

« - Required, not open

« - I trust you and will not fill in the advertising link