JS Modular-requirejs

Source: Internet
Author: User

1. Why Use Require.js

In the beginning, Web pages need to use a lot of different plug-ins, are loaded sequentially, you need to be aware of the loading sequence is the dependency relationship.

   <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>

There are a lot of shortcomings in this notation. First of all, when loading, the browser will stop the page rendering, the more files loaded, the page will lose the response time is longer;

Secondly, due to the existence of a dependency between the JS files, it is necessary to strictly guarantee the loading order (for example, 1.js in front of 2.js), the most dependent

Modules must be put to the last load, and when the dependencies are complex, code writing and maintenance can become difficult.

The role of 1.1 require.js

① to realize the asynchronous loading of JS file, to avoid the Web page loss of response;

② the dependencies between the management modules for easy code writing and maintenance.

2. Use of Require.js

loading of 2.1 require.js

2.1.1 The first step in using Require.js is to go to the official website to download the latest version first.

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

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

The async attribute indicates that the file needs to be loaded asynchronously to prevent the webpage from losing its response. IE does not support this property, only support defer, so put defer also write on.

This line can also be loaded at the bottom of the page.

2.1.2 loading require.js, the next step will be to load our own code. Suppose our own code file is Main.js, also placed under the JS directory. Well, just write the following:

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

The purpose of the Data-main property is to specify the main module of the Web program. In the example above, is the JS directory below the main.js, this file will be the first to be loaded require.js.

Since the require.js default file suffix is JS, main.js can be shortened to main.

This is my JS directory.

2.2 the main module

With the Require method, the module load of the code is implemented, and the Require () function accepts two parameters:

① The first parameter is an array that represents the dependent modules, such as ["JQuery", "underscore", "backbone"], i.e. the main module relies on these two modules;

② The second parameter is a callback function that will be called when the module specified by the current polygon is loaded successfully. The loaded module is passed into the function as a parameter.

These modules can then be used inside the callback function. The callback function is the JS code for the entire page.

function ($, _, Backbone) {});

loading of the 2.3 module

1, by default, Require.js assumes that the two modules are in the same directory as Main.js, the filenames are jquery.js,underscore.js, and then loaded automatically. Use

Require.config () method, we can customize the load behavior of the module.

Require.config is used to configure the module load location, simply to give the module a shorter and better-remembered name.

Require.config ({paths: {"jquery":  ["Http://libs.baidu.com/jquery/2.0.3/jquery", "Jquery-3.1.1.min"], "Underscore": "Underscore" }); 

Require.config () is written on the head of the main module main.js. A parameter is an object that specifies the load path for each module by the paths property of the object.

Paths also has an important function, that is, you can configure multiple paths, and if the remote CDN Library is not loaded successfully, you can load the local library.

2, the above code gives three module file name, the path default and main.js in the same directory (JS subdirectory). If these modules are in a different directory,

such as the Js/lib directory, there are two ways to do it. One is to specify the path individually.

require.config ({    paths: { "jquery": "Lib/jquery", "underscore": "Lib/underscore"  }});

The other is to directly change the base directory BaseURL:

"Js/lib", paths: { "jquery": "jquery", "underscore": "Underscore" }});

3. Loading non-normalized modules

The Shim property is specifically designed to configure incompatible modules. Specifically, each module should be defined

The ①exports value (the variable name of the output) indicating the name of the external invocation of the module;

A ②deps array that indicates the dependency of the module.

For example, the plugin for jquery can be defined like this:

require.config ({    "js/lib", shim: { ' underscore '_ ' }, ' Backbon E ': {deps: [' underscore ', ' jquery '' Backbone ' }} paths: { "jquery": "JQ Uery ", " underscore ":" Underscore " }});

2.4 AMD module notation

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

define (function () {});

② If the module also relies on other modules, then the first parameter of the Define () function must be an array that indicates the dependency of the module.

define ([' jquery '], function (jquery) {});

3. Example

1. student.js File:

Define (function() {    return  {        function(name, gender) {             return {                name:name,                gender:gender            };};    });

2. class.js File:

Define (function() {        var allstudents = [];         return {            "001",            "Computer",            function(student) {                Allstudents.push (student);            },            function() {                return  allstudents;};}    );

3. manager.js File:

function (student, CLZ) {    return  {        function(name, gender) {            Clz.addtoclass (student.creatstudent (name, gender));        },        function() {             return clz.getclasssize ();        }    };});

4. main.js File:

function (manager) {      manager.addnewstudent ("Jack", "male");      Manager.addnewstudent ("Rose", "female");      

JS Modular-requirejs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.