Requirejs First Knowledge

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

With the gradual enrichment of Web site features, JS is also more and more, in the past through the script tag introduced by the way has not been able to meet the Internet development model, so REQUIREJS can provide us with two kinds of solutions:

1 Modular Organization JS

2 Loading JS files asynchronously

With these two solutions, we can effectively help us solve the organizational challenges of the front-end code base.

Here's an example of a simple primer:

Index.html

<! DOCTYPE html>require.config ({paths:{"jquery": ["Http://libs.baidu.com/jquery/2.0.3/jquery", "js/ jquery-1.11.3 "]," a ":" js/a "})require ([" jquery "," a "],function ($) {$ (function () {alert (" Load Finished ") }); </script>    

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>

In the example above, a module is defined by the Define function in A.js and then used in the page

Require (["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, As in the above example, execute alert ("Load finished") after loading a.js;

The above index.html in the Require.config, require.config is used to configure the module loading location, the simple point is to give the module a shorter and better remember the name, such as Baidu's jquery library address marked as jquery , so in require only need to write You ["jquery"] can load the JS, local JS We can also configure this, through the paths configuration will make our module name more refined, paths also has an important function, is to 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

In the above example, the Require.config configuration needs to be applied on each page, which is very not elegant, and Requirejs provides a "main module" function: First we 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="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 ({    "js"})

Loading non-canonical modules

In theory, require.js-loaded modules must be modules defined in accordance with the AMD specification, with the Define () function. But in fact, even though some popular libraries (such as jquery) are already in compliance with the AMD specification, more libraries don't fit. So, is require.js able to load non-canonical modules?

The answer is yes.

Such modules are used to define some of their characteristics before they are loaded with require (), using the Require.config () method.

For example, both underscore and backbone are not written in 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 that, in addition to the paths property mentioned previously, has a shim property that is specifically designed to configure incompatible modules. Specifically, each module defines (1) The exports value (the output variable name), indicating the name of the external invocation of the module, and (2) An array of deps that indicates the dependency of the module.

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

Shim: {' Jquery.scroll ': {deps: [' jquery '], exports: ' JQuery.fn.scroll '}}

require.js plug-in

Require.js also offers a range of plugins for 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});

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

define ([  'text!review.txt',  'image!cat.jpg' 
     ], function (review,cat) {console.log (review);    Document.body.appendChild (CAT); });

Similar plugins include JSON and Mdown, which are used to load JSON files and markdown files.

Requirejs First Knowledge

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.