Requirejs Getting Started learning

Source: Internet
Author: User

Objective

   Recently on the Internet, groups of all kinds of casual look, casually learn. Summer internship has not been found, yesterday opened a question, study well. Recently have seen the front-end of the Adm,cmd specification, and then on-line looking for information, read a number of cattle people's blog, write very good, and then self-feeling to understand the point, between I still belong to the rookie level, the article inevitably has errors, hope points to correct.

ADM Specification

AMD is the abbreviation for "Asynchronous module definition", meaning "async module definition". It loads the module asynchronously, and the module's load does not affect the execution of the statement behind it. All statements that rely on this module are defined in a callback function that will not run until the load is complete. The AMD specification is actually a modular management of our JS files.

Why to use Require.js

  At the earliest, all JavaScript code was written in a single file, as long as the file was loaded. Later, the code more and more, a file is not enough, must be divided into multiple files, loaded sequentially. The following page code, I believe many people have seen.

  

<script scr="1.js"></script><script scr="2.js" ></script><script scr="3.js"></script><script scr="  4.js"></script>

This code loads multiple JS files in turn. This kind of writing has a lot of shortcomings. First of all, when loading, the browser stops the page rendering, the more files loaded, the longer the Web page loses response time, and secondly, because of the existence of a dependency between JS files, Therefore, the load order must be strictly guaranteed (for example, 1.js above 2.js), the most dependent module must be put to the last load, when the dependency is very complex, code writing and maintenance will become difficult.

The birth of require.js is to solve these two problems:

(1) To realize the asynchronous loading of JS file, to avoid web page loss response.

(2) The dependency between the management module, easy to write and maintain the code.

A small example of require.js

The following is a very simple small example to use Require.js.

First, load Require.js

Go to the official website to download good require.js after. Here it is placed in the JS folder of our project directory. Load the require.js in our HTML file.

<!DOCTYPE HTML Public "-//W3C//DTD XHTML 1.0 transitional//en" "http://www.w3.org/TR/xhtml1/DTD/ Xhtml1-transitional.dtd "><HTMLxmlns= "http://www.w3.org/1999/xhtml"><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8" /></Head><Body>    <P>Hello world!</P>    <Scriptsrc= "Js/require.js"Data-main= "Js/main"></Script></Body></HTML>

here to avoid loading JS files may cause the webpage to lose its response. We put JS on the bottom of the page to load, another way is:

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

Second, the main module main.js

In the above <script> there is a sentence: data-main= "Js/main", here main.js is the entire page of the entry code, we call it "the main module."

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.

Here's a look at the code in Main.js.

require.config ({    paths:{        "jquery": "jquery-1.11.3",        "math": "Math"    },    }); require ([' math '],function(math) {    console.log (Math.add);});

here the Main.js relies on a module: math.

The Require () function accepts two parameters. The first parameter is an array that represents the module on which it is dependent. Above we rely on the math.js. 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 passes in the function as a parameter, allowing the modules to be used inside the callback function.

if the main module relies on multiple modules, you can write this:

Require ([' Math ', ' jquery ', ' backbone '),function(math, $, backbone) {    //  code here });

Require.js will load the three modules before running the callback function. The main function code is written in the callback function. The order of the parameters in the callback function is consistent with the order in the dependent module array.  

By default, Require.js assumes that the above three modules are in the same directory as Main.js, with filenames math.js,jquery.js and backbone.js, and then loaded automatically.

Using the Require.config () method, we can customize the load behavior of the module. 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 can use relative paths or absolute paths.

How AMD modules are written

Require.js loaded modules, using AMD specifications. In other words, the module must be written in accordance with AMD's requirements.

Specifically, 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.

the math.js in the above example:

define ([' jquery '],function($) {    varfunction(A, b        ) {  Return  {            + B,            innertext:$ ("P"). Text ()        }    };     return {        add:add    };    });

Here our math.js again relies on the jquery module, which gets the innerhtml of the element p in the callback function. (This is just a demo of the math module and can depend on other modules).

A JS object is returned inside the callback function.

In the require () callback function of the main module, we can call the Math.add method. It also calls the jquery module to get the text () of the element p.

Conclusion

Blogging is also a technical work, the level is limited, the article has a lot of knowledge points not mentioned. We can look at the original article of The Ox Man: http://www.ruanyifeng.com/blog/2012/11/require_js.html,

Http://www.cnblogs.com/snandy/archive/2012/05/24/2514700.html. Or insist on writing a blog, the process of blogging you will find that there are actually a lot of you think you understand, but to really speak out when still some knowledge of their own foggy. Study hard, try to find an internship to learn in practice, from a too stupid, blind learning progress or pretty slow.

Requirejs Getting Started learning

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.