Requirejs-javascript modularity (I. Introduction)

Source: Internet
Author: User
Tags define function

1. Know Requirejs

Requirejs official website (http://requirejs.org/) Description:

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.

Requirejs is a JS file to load the module, it is an optimized design on the browser side, and it can be used in other JS environment, such as rhino and node, using a Requirejs-like JS module loader can improve the speed and quality of your code execution

2. Using Requirejs

(1) Usually we quote JS Way

Index.html

<!DOCTYPE HTML><HTML><Head><MetaCharSet= "Utf-8" /><Scripttype= "Text/javascript"src= "Js/my/dr.js"></Script><title></title></Head><Body><P>This is index.html</P><Script>Console.log ("dr.version:"+dr.version);</Script></Body></HTML>

Js/my/dr.js

function (window) {var dr == "v1.0"= Dr;} (window);
Console output
dr.version:v1.0

(2) How to quote Requirejs

A simple example:

Directory structure:

Index.html

<!DOCTYPE HTML><HTML>    <Head>        <MetaCharSet= "Utf-8" />        <Scripttype= "Text/javascript"src= "Js/require.js"Data-main= "Js/main"></Script>        <title></title>    </Head>    <Body>        <P>This is index.html</P>    </Body></HTML>

Js/my/dr.js

function (window) {
var dr = {}; = "v1.0"; = Dr; Define ( function () { return Dr; }); (window);

Js/main.js

require.config ({    "js",    paths: {        "my/dr"    }}) require ([function  (DR) {    if  (DR) {        Console.log ("Dr.js is ready!" );
Console.log ("dr.version:" + dr.version); })

Test, console output:

Dr.js is ready! dr.version:v1. 0

1, look at the index.html.

The Require JS file is introduced in the

2, look at the "entrance" of the Requirejs main.js.

Require.config (): Configures basic information for require.

BaseURL if not specified, the default is the Main.js folder path, that is, "JS", our code does not write BaseURL property is irrelevant, because we and main folder path is consistent;

Path: We want to refer to the JS file and path, if you want to refer to multiple JS files, append can, but here we refer to the JS file must conform to the AMD specification (asynchronous module loading mechanism) can, simply speaking, must have the Define () method.

Require (): two parameters, the first is an array, which contains the name of the JS file we want to refer to, and the name of the paths in the Config method above, the second is a reference to the completion of the callback function, in this function has a parameter, this parameter value is the JS file define ( ) The return value of the method.

3, look at the Dr.js

function (window) {    var dr = {};     = "v1.0";     = Dr;   Define (   function() { return    Dr; }); (window);

This is the same as before (1) usually we refer to JS method , compared to a define function (italic part), this function returns the Dr object. This is in line with the AMD specification and we can get the dr.version value in the callback function of Main.js's require ().

Simply summarize below:

1. Define the Define () method in the JS file we need to refer to to return an object.

2, write the Main.js method (of course, the name is written anything, as long as the index refers to the Requirejs file, the value of the property data-main the corresponding main.js can be). Write the configuration file (specify baseurl,paths inside the JS file we want to refer to, here JS file is as module of the way to be require asynchronous loading)

3, the introduction of Requirejs file in index.html, specify the Require portal, in the page can be used.

Here are my examples of loading two modules (Dr.js and Jquery.js), which are simple enough to be understood at a glance.

Directory structure:

(incorrect picture, the jquery folder is modified for JQ when testing later)

Follow the steps to:

1. Write the Define () method in Dr.js and Jquery.js. Dr.js we've just written it, there's no change here, what about jquery? Look at the jquery Source:

//Expose JQuery as an AMD module with only for AMD loaders that//understand the issues with loading multiple versions of JQuery//In a page, all might call define (). The loader would indicate//They has special allowances for multiple jQuery versions by//Specifying Define.amd.jQuery = True. Register as a named module,//since JQuery can is concatenated with and other files The may use define,//But does use a proper concatenation script that understands anonymous//AMD modules. A named AMD is safest and the robust to register.//lowercase jquery is used because AMD module names be derived from//file names, and JQuery is normally delivered in a lowercase file name.//Do this after creating, the global So, if, AMD module wants to call//Noconflict to hide this version of JQuery, it 'll work.if(typeofdefine = = = "function" && define.amd &&define.amd.jQuery) {define ("jquery", [],function() {returnJQuery;} );}

Already see that jquery has been written, make jquery an asynchronous-loaded module implementation.

2, write Main.js, add the configuration of jquery in paths, the name "jquery", the path is "Jq/jquery", represents the introduction of "js/jq/" under the Jquery.js file, Note: Here the path cannot write suffix ". js" Add a module for jquery in require .

require.config ({    "js",    paths: {        "jq/jquery",        "My/dr"    }}) Require ([function($, DR) {    if  ($) {        console.info ("jquery Is ready! " );        Console.log ("jquery version:" +$ (). jquery);    }     if (DR) {        console.info ("Dr.js is ready!" );        Console.log ("dr.version:" + dr.version)    })

3, index.html, add a button to test whether jquery and Dr are properly introduced

<! DOCTYPE html> This is index.html</p>        <button onclick= "getversion (); > Get version </button>        <script>            function  getversion () {                Console.log (" Index-->jquery version: "+ $ (). jquery);                Console.log ("INDEX-->DR version:" + dr.version);            }         </script>    </body>

Test:

jquery is ready!
jquery version:1.9.1
Dr.js is ready!
dr.version:v1.0

Console output when you click button
Index-->jquery version:1.9.1
INDEX-->DR version:v1.0

Here's a big question: If we remove the function wrapper for GetVersion (), write it directly in the script.

Console.log ("Index-->jquery version:" + $ (). jquery);

Or

Console.log ("INDEX-->DR version:" + dr.version);

What's going to happen?

Uncaught Referenceerror: $ is not defined

jquery is ready!
jquery version:1.9.1
Dr.js is ready!
dr.version:v1.0

Or

Uncaught REFERENCEERROR:DR is not defined

jquery is ready!
jquery version:1.9.1
Dr.js is ready!
dr.version:v1.0

The root of the problem is that when Requirejs asynchronously loads jquery and Dr, the index.html's document flow has been read, so an error occurs, and then asynchronously gets the callback function that require loads jquery and Dr to complete.

Requirejs-javascript modularity (I. Introduction)

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.