JavaScript Modular Tools Requirejs Tutorial

Source: Internet
Author: User
Tags define function script tag jquery library

Transferred from: http://www.w3cschool.cc/w3cnote/requirejs-tutorial-1.html, http://www.w3cschool.cc/w3cnote/requirejs-tutorial-2.html

With the website features gradually enriched, the page JS also become more and more complex and bloated, the original through the script tag to import a JS file this way has been unable to meet the current Internet development model, we need team collaboration, module reuse, unit testing and a series of complex needs.

Requirejs is a very compact JavaScript module loading framework and is one of the best implementations of the AMD specification. The latest version of Requirejs is only 14K compressed and is very lightweight. It can also work with other frameworks, and using Requirejs will certainly improve the quality of your front-end code.

What benefits Requirejs can bring

Official description of the Requirejs:

Requirejs is a JavaScript file and module loader. It's optimized for in-browser use, but it can be used in the other JavaScript environments, like Rhino and Node. Using a modular script loader like Requirejs would improve the speed and quality of your code.

General meaning:

In the browser can be as a JS file module loader, also can be used in the node and Rhino environment, Balabala .... This passage describes the basic function of Requirejs "modular loading", what is modular loading? We're going to explain one by one of the space that follows.

Let's take a look at a common scenario and explain how to use Requirejs with examples.

Normal Writing method

Index.html:

<! DOCTYPE html>

A.js:

function fun1 () {  alert ("It Works");} Fun1 ();

Maybe you'd prefer to write like this.

(function () {    function fun1 () {      alert ("It Works");    Fun1 ();}) ()

The second method uses the block scope to declare the function to prevent pollution of the global variables, the essence is the same, when running the above two examples do not know whether you notice that when the alert executes, the HTML content is blank, that is <span>body</span> not displayed, when clicked OK, it appears, This is the result of JS blocking browser rendering .

Requirejs notation

Of course, first of all to the Requirejs website to download JS-and Requirejs.rog
Index.html:

<! DOCTYPE html>

A.js:

Define (function () {    function fun1 () {      alert ("It Works");    Fun1 ();})

Browser prompted the "it works", stating that the operation is correct, but a little different, this browser is not a blank, the body has appeared in the page, so far can know Requirejs has the following advantages:

    1. Prevents JS loading from blocking page rendering
    2. Use program calls to load JS, prevent the appearance of the following ugly scene
<script type= "Text/javascript" src= "a.js" ></script><script type= "Text/javascript" src= "B.js" > </script><script type= "Text/javascript" src= "c.js" ></script><script type= "Text/javascript" Src= "D.js" ></script><script type= "Text/javascript" src= "e.js" ></script><script type= "text /javascript "src=" f.js "></script><script type=" Text/javascript "src=" G.js "></script>< Script type= "Text/javascript" src= "h.js" ></script><script type= "Text/javascript" src= "I.js" ></ Script><script type= "Text/javascript" src= "J.js" ></script>

JS Modular Tools Requirejs Tutorial (a): First knowledge Requirejs we introduced Requirejs in a very simple way, this article will cover some of the basics of Requirejs, including how to use the API.

Basic API

Require defines three variables: Define,require,requirejs, where require = = = Requirejs, generally using require shorter

    • Define can see from the name that this API is used to define a module
    • Require load the dependent module and execute the post-load callback function

A.js in the previous article:

Define (function () {    function fun1 () {      alert ("It Works");    Fun1 ();})

A module is defined by the Define function and then used in the page:

Require (["js/a"]);

To load the module ( note that the dependency in require is an array, even if there is only one dependency, you must also use an array to define ), the second parameter of the Requir API is callback, a function that is used to handle the logic after loading, such as:

Require (["js/a"],function () {    alert ("Load finished");})
Loading files

In the previous example, the loading module is local JS, but in most cases the page needs to load the JS may be from the local server, other Web site or CDN, so it can not be loaded in this way, we load a jquery library as an example:

Require.config ({    paths: {        "jquery": ["Http://libs.baidu.com/jquery/2.0.3/jquery"]       }}) require ([" jquery "," js/a "],function ($) {    $ (function () {        alert (" Load finished ");      })})

This side involves require.config , require.config is used to configure the module loading location, simple point is to give the module a shorter better remember the name, such as Baidu's jquery library address marked as jquery , so in require only need to write ["jquery"] can load the JS, Local JS We can also configure:

Require.config ({    paths: {        "jquery": ["Http://libs.baidu.com/jquery/2.0.3/jquery"],        "a": "js/a"       }}) Require (["jquery", "a"],function ($) {    $ (function () {        alert ("Load finished");      })})

The paths configuration will make our module name more refined, paths also has an important function, that is, you can configure multiple paths, if the remote CDN Library is not loaded successfully, you can load the local library, such as:

Require.config ({    paths: {        "jquery": ["Http://libs.baidu.com/jquery/2.0.3/jquery", "Js/jquery"],        "a": " js/a "       }}) require ([" jquery "," a "],function ($) {    $ (function () {        alert (" Load Finished ")})      )

After this configuration, when Baidu's jquery does not load successfully, it will load the local JS directory of jquery

    1. When using Requirejs, loading the module without writing .js suffixes, of course, can not write the suffix
    2. The callback function in the example above is found to have $ parameters, this is the output variable of the dependent jquery module, if you rely on multiple modules, you can write several parameters in turn to use:
Require (["jquery", "underscore"],function ($, _) {    $ (function () {        _.each ([1,2,3],alert);    })})

If a module does not output variable values, then do not, so try to write the output module in front, to prevent confusion caused misunderstanding

Global configuration

The above example repeats the require.config configuration, if each page is added to the configuration, it must be very indecent, Requirejs provides a function called "Master data", we first create a main.js:

Require.config ({    paths: {        "jquery": ["Http://libs.baidu.com/jquery/2.0.3/jquery", "Js/jquery"],        "a": " js/a "       }})

Then use Requirejs in the following way on the page:

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

To explain, the script tag loading Requirejs has added data-main properties, this property specifies that JS will be processed after loading the reuqire.js, we will require.config add the configuration to data-main each page to use this configuration, The page can then be used directly require to load all the short module names

data-mainThere is also an important function, when the script tag specifies the Data-main property, require will default to data-main the specified JS as the root path, what does it mean? As set above data-main="js/main" , after we use require([‘jquery‘]) (do not configure jquery paths), require will automatically load js/jquery.js this file, rather than jquery.js, equivalent to the default configuration:

Require.config ({    baseUrl: "JS"})
Third-party modules

By require loading the module is generally required to comply with the AMD specification is used define to declare the module, but part of the need to load non-AMD specification JS, this time need to use another function: Shim,shim interpretation is also difficult to understand, Shim directly translated as "pad", In fact, there is the meaning of this, at present I mainly used in two places
1. Non-AMD module output, the non-standard AMD module "pad" into a usable module, for example: in the old version of jquery, is not inherited AMD specifications, so can not directly require["jquery", this time need shim, For example, if I use the underscore class library, but he does not implement the AMD specification, then we can configure

Require.config ({    shim: {        "underscore": {            exports: "_";        }}    )

With this configuration, we can refer to the underscore module in other modules:

Require (["underscore"], function (_) {    _.each ([+], alert);})

Plug-in form of non-AMD modules, we often use jquery plug-ins, and these plug-ins are not compatible with AMD specifications, such as the Jquery.form plug-in, this time need to put the form plug-in "pad" into jquery:

Require.config ({    shim: {        "underscore": {            exports: "_";        },        "Jquery.form": {            deps: [" jquery "]        }}}    )

can also be abbreviated as:

Require.config ({    shim: {        "underscore": {            exports: "_";        },        "Jquery.form": ["jquery"]    }})

After this configuration, we can use jquery after the plugin is loaded.

Require.config (["jquery", "jquery.form"], function ($) {    $ (function () {        $ ("#form"). Ajaxsubmit ({...})    })

Well, the basic configuration of Requirejs is roughly that much, and there are some extended features that will be mentioned in the following space

Article Source: HTTPS://GITHUB.COM/LIUXEY/BLOG/ISSUES/2

JavaScript Modular Tools Requirejs Tutorial

Related Article

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.