Ruan Yifeng blog for the introduction of RequireJS is relatively easy to understand, reprint today! (Only for their own review only, involving infringement please contact me)


Why require.js?

In the early days, all the Javascript code was written in a single file, and it was enough to load that single file. Later, more and more code, one file is not enough, must be divided into multiple files, load one after another. The following page code, I believe many people have seen.

<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>Copy the code

This code loads multiple JS files in turn.

There are major disadvantages to writing this way. First, when loading, the browser will stop rendering the page, and the more files loaded, the longer the page will be unresponsive. Secondly, due to the dependency relationship between JS files, the loading sequence must be strictly guaranteed (for example, 1.js should be in front of 2.js), and the module with the largest dependency must be loaded last. When the dependency relationship is very complex, the writing and maintenance of the code will become difficult.

Require.js was created to solve these two problems:

(1) Realize asynchronous loading of JS files to avoid losing response of web pages;

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

2, require. Js loading

The first step to using require.js is to download the latest version from the official website.

Once downloaded, assuming you put it under the JS subdirectory, you’re ready to load.

<script src="js/require.js"></script>Copy the code

One might imagine that loading this file would also cause the page to become unresponsive. There are two solutions. One is to load it at the bottom of the page, and the other is to write it like this:

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

The async property indicates that the file needs to be loaded asynchronously to prevent the page from becoming unresponsive. IE doesn’t support this property and only supports defer, so write defer as well. In my previous article about front-end performance optimization, I mentioned defer. If you are interested, check it out! www.haorooms.com/post/web_xn… After loading require.js, the next step is to load our own code. Suppose our own code file is main.js, also in the js directory. So, all you need to do is write:

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

The data-main property specifies the main module of the web application. In this case, the main.js file under the js directory will be the first to be loaded by require.js. Since require.js’s default file suffix is js, you can simply write main.js as main.

Three, the writing method of the main module

In the previous section, I called main.js the “main module,” which means the entry code for the entire web page. It’s a bit like the MAIN () function in C, where all the code starts running.

Here’s how to write main.js.

If our code doesn’t depend on any other modules, we can write javascript code directly.

// main.js
alert("Loading successful!");Copy the code

But in this case, there is no need to use require.js. What is really common is for the main module to depend on other modules, in which case the REQUIRE () function defined by the AMD specification is used.

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

The require() function takes two arguments. The first argument is an array of dependent modules, such as [‘moduleA’, ‘moduleB’, ‘moduleC’], where the main module depends on these three modules. The second argument is a callback function that will be called after all the modules specified in the previous page have been successfully loaded. Loaded modules are passed to the function as arguments, so they can be used inside the callback function.

Require () asynchronously loads moduleA, moduleB, and moduleC without the browser losing its response; It addresses the dependency problem by specifying a callback function that will run only after all previous modules have been successfully loaded.

Now, let’s look at a practical example.

Assuming that the main module relies on jquery, underscore, and backbone, main.js can be written like this:

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

Require. js loads jQuery, underscore, and backbone before running the callback function. The main module code is written in the callback function.

4. Module loading

In the example at the end of the previous section, the dependency modules for 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.

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). The parameter is an object whose Paths property specifies the loading path for each module.

The require. Config ({paths: {"jquery": "jquery.min"."underscore": "underscore.min"."backbone": "backbone.min"}});Copy the code

The above code gives the file names of the three modules, and the default path is in the same directory as main.js (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 paths one by one.

The require. Config ({paths: {"jquery": "lib/jquery.min"."underscore": "lib/underscore.min"."backbone": "lib/backbone.min"}});Copy the code

The other is to change the base directory directly.

The require. Config ({baseUrl:"js/lib"The paths: {"jquery": "jquery.min"."underscore": "underscore.min"."backbone": "backbone.min"}});Copy the code

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

The require. Config ({paths: {"jquery": "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min"}});Copy the code

Require.js requires that each module be a separate JS file. In this way, if you load multiple modules, you will make multiple HTTP requests, which will affect the loading speed of the web page. Therefore, require.js provides OPTIMIZER, an optimization tool that can be used to combine multiple modules into a single file to reduce the number of HTTP requests once modules are deployed. Tools to address: requirejs.org/docs/optimi… For this tool to be based on Node, you also need github.com/jrburke/r.j… The js.

Five, AMD module writing method

Require. js loading module, using AMD specifications. That is, modules must be written as specified by AMD.

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

Suppose you now have a math.js file that defines a Math module. So math.js would look like this:

// math.js
define(function() {var add =function(x,y){returnX + y. };return{the add: add}; });Copy the code

The loading method is as follows:

/ / the main js the require (['math'].function(math) {alert (math. The add (1, 1)); });Copy the code

If the module also depends on other modules, the first argument to define() must be an array that specifies the module’s dependencies.

define(['myLib'].function(myLib){function foo() {myLib. DoSomething (); }return{foo: foo}; });Copy the code

When the require() function loads the module above, it loads the mylib.js file first.

Load non-standard modules

In theory, modules loaded by require.js must be modules defined by define() in accordance with AMD specifications. But in practice, while some popular libraries (such as jQuery) are AMD compliant, many more are not. Can require.js load non-canonical modules?

The answer is yes.

Before such modules can be loaded with require(), some of their characteristics are defined using the require.config() method.

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

The require. Config ({shim: {'underscore': {exports:'_'},'backbone': {deps:'underscore'.'jquery'], exports:'Backbone'}}});Copy the code

Require.config () accepts a configuration object that, in addition to the paths property described earlier, has a shim property for configuring incompatible modules. Specifically, each module defines an (1) exports value (the name of the exported variable) that indicates the name of the external call to 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'}}Copy the code

7. Require.js plugin

Require.js also provides a series of plug-ins that implement specific functions.

The domReady plugin allows the callback function to run after the page DOM structure has been loaded.

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

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) {the console. The log (review); Document. The body. The appendChild (cat); });Copy the code

Similar plug-ins are JSON and mDOWN for loading JSON files and markdown files.

Statement:

This article content, mostly from the nguyen other blog, www.ruanyifeng.com/blog/2012/1…

    PREVIOUS:
    NEXT:
    HTML meta summary, THE use of META attributes in HTML tags
    HTML code is highlighted, JS code is highlighted

Tags: requirejs, js

Related articles:

  • Requirejs Optimizer merges and compresses the Require project
  • RequireJs use and quick understanding
  • RequireJS loads modularized
  • Es6 commonly used string, array, object extension and application
  • [js tool]js extraction of Chinese pinyin initials method
  • Reprint a few front-end flow charts, including front-end JS basic knowledge
  • Summary of DOM manipulation in JS
  • Some browser parsing of es Modules
  • What are deep and shallow JS copies and how to implement them