JavaScript Modular Programming

Source: Internet
Author: User
Tags jquery library

(a): how the module is written

Web pages are becoming more and more like desktop programs, requiring a collaborative team, schedule management, Unit testing, etc... Developers have to use the software engineering approach to manage the business logic of the Web Page.

JavaScript modular programming has become an urgent requirement. ideally, developers only need to implement core business logic, and others can load modules that others have already written.

however, JavaScript is not a modular programming language, it does not support the class, not to mention the Module. (the ECMAScript Standard Sixth edition, which is under development, will officially support "class" and "module", but it still takes a long time to put into practice.) )

The JavaScript community has made a lot of efforts to achieve the "module" effect in the existing operating Environment. This article summarizes the current "JAVASCRIPT modular programming" best practices and shows how to put it into practice. Although this is not a beginner tutorial, you can understand the basic syntax of JavaScript a little bit.

first, the original wording

A module is a set of methods for implementing a specific Function.

Simply put the different functions (and the variables that record the State) together, even if it is a module.

Function M1 () {
//...
}

function m2 () {
//...
}

The above functions M1 () and M2 () to form a module. When used, call directly on the LINE.

The disadvantage of this approach is Obvious: "pollute" the global variable, there is no guarantee that the variable name conflicts with other modules, and the module members do not see a direct relationship.

Ii. the wording of the object

In order to solve the above shortcomings, the module can be written as an object, all the module members are placed in this Object.

var moduleone= ({

"count": 0,
"one": function () {

Dosomting

},

"both": function () {

Dosomting

}

});

Iii. immediate execution of function notation

Using the Execute functions now (immediately-invoked function expression,iife), You can achieve the purpose of not exposing private members.

var module1 = (function () {

var _count = 0;

var m1 = function () {
//...
};

var m2 = function () {
//...
};

return {
m1:m1,
M2:m2
};

})();

Using the notation above, the external code cannot read the internal _count variable.

Console.info (module1._count); Undefined

Module1 is the basic way of writing JavaScript modules. The following, and then processing the Writing.

four, wide magnification mode (Loose Augmentation)

In a browser environment, parts of the module are usually obtained from the web, and sometimes it is not possible to know which part is loaded First. If you use the previous section, the first part of the execution is likely to load a nonexistent empty object, then use the "wide magnification mode".

var module1 = (function (MOD) {

//...

Return mod;

}) (window.module1 | |  {}); Pass-through constructor function object assigns an empty object after an empty object is passed without an object

V. INPUT global Variables

Independence is an important feature of the module and it is best not to interact directly with other parts of the Program.

In order to call global variables inside a module, you must explicitly enter other variables into the Module.

var module1 = (function ($, YAHOO) {

//...

}) (jQuery, YAHOO);

The above Module1 module needs to use the jquery library and Yui library, the two libraries (actually two modules) as a parameter input module1. In addition to ensuring the independence of the module, it also makes the dependency between modules Obvious.

JavaScript Modular programming (ii): AMD Specifications

VII. Specification of modules

First think about why the module is important?

Because of the module, we can more easily use other People's code, want what function, load what Module.

however, This has a premise, that is, we must write the module in the same way, otherwise you have your writing, I have my writing, it is not messy set! This is even more important considering that the JavaScript module does not yet have an official Specification.

currently, There are two types of JavaScript module specifications available: Commonjs and Amd. I mainly introduce amd, but start with commonjs.

eight, CommonJS

In 2009, American programmer Ryan Dahl created the Node. JS project to use the JavaScript language for Server-side programming.

Node's Advent Logo "javascript Modular programming" was formally born. Because frankly speaking, in the browser environment, No module is not particularly big problem, after all, the complexity of the Web-page program is limited, but on the server side, must have modules, and the operating system and other applications to interact with, otherwise it is impossible to Program.

Node. Js's module system is implemented with reference to the Commonjs Specification. In commonjs, there is a global method require () that is used to load the Module. Assuming that a mathematical module is math.js, it can be loaded as Follows.

var math = require (' math ');

Invocation mode

var math = require (' math ');
Math.method ();

Since this series is primarily for browser programming and does not involve Node. js, there is no more introduction to Commonjs. As long as we know here, require () is used to load the module on the LINE.

The second line, method (), runs after the first line require (' math '), so the math.js load must be Completed. That is, if the load time is long, the entire application will stop there and so On.

This is not a problem on the server side, because all the modules are stored on the local hard disk, can be loaded synchronously, waiting time is the hard disk read Time. however, for the browser, this is a big problem, because the modules are placed on the server side, the waiting time depends on the speed of the network, it may take a long time, the browser is in "suspended animation" status.

As a result, the Browser-side module cannot be "synchronous-loaded" (synchronous) and can only take "asynchronous load" (asynchronous). This is the background to the birth of the AMD Specification.

X. AMD

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.

AMD also uses the Require () statement to load the module, but unlike commonjs, it requires two parameters:

Require ([module], callback);

The first parameter, [module], is an array in which the member is the module to be loaded, and the second parameter, callback, is the callback function after the load SUCCEEDS. If you rewrite the previous code in AMD form, this is the following:

Method () is not synchronized with the math module, and the browser does not take place in Animation. So it's clear that AMD is better suited for a browser environment.

currently, There are two main JavaScript libraries that implement the AMD Specification: Require.js and Curl.js. The third part of this series will introduce require.js to further explain Amd's usage and how to put modular programming into combat.

JavaScript Modular Programming (iii): usage of require.js

first, Why 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 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>

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.

second, the loading of require.js

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" ></script>

One might think that loading this file could also cause the webpage to lose its response. There are two solutions, one is to put it on the bottom of the page to load, the other is written as Follows:

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

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

three, The main module of the wording

In the previous section of the main.js, I called it the "main module", meaning the entry code for the entire Page. It's kind of like the c-language main () function, where all the code starts RUNNING.

See below, How to write Main.js.

If our code does not depend on any other modules, then you can write the JavaScript code directly.

Main.js

Alert ("loaded successfully! ");

But in this case, there is no need to use the Require.js. The real common scenario is that the main module relies on other modules, and the Require () function defined by the AMD specification is Used.

Main.js

Require ([' Modulea ', ' Moduleb ', ' Modulec '], function (modulea, moduleb, MODULEC) {

Some code here

});

The Require () function accepts two Parameters. The first parameter is an array that represents the dependent module, The example above is [' Modulea ', ' Moduleb ', ' Modulec ', i.e. the main module relies on these three modules; the second parameter is a callback function, which is 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.

Require () asynchronously loads Modulea,moduleb and modulec, the browser does not lose its response; it specifies a callback function that only the preceding modules will run after they are successfully loaded, resolving the dependency Problem.

below, let's look at a practical example.

Assuming that the main module relies on the three modules of jquery, underscore, and backbone, Main.js can write this:

Require ([' jquery ', ' underscore ', ' backbone '), function ($, _, backbone) {

Some code here

});

Require.js will load jquery, underscore, and backbone before running the callback Function. The code for the main module is written in the callback Function.

Iv. Loading of modules

In the last example of the previous section, the dependency module of the main module is [' jquery ', ' underscore ', ' backbone ']. By default, Require.js assumes that the three modules are in the same directory as main.js, with filenames jquery.js,underscore.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.

Require.config ({

paths: {

"jquery": "jquery.min",
"underscore": "underscore.min",
"backbone": "backbone.min"

}

});

The above code gives the file name of three modules, and the path defaults to 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 ({

Baseurl: ' lib/',

paths: {

"jquery": "jquery.min",
"underscore": "underscore.min",
"backbone": "backbone.min"

}

});

If a module is on a different host, you can also specify its URL directly, for example:

Require.config ({

paths: {

"jquery": "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min"

}

});

Require.js requirements, Each module is a separate JS File. In this case, if multiple modules are loaded, the HTTP request will be issued multiple times, which will affect the load speed of the Web Page. As a result, require.js provides an optimization tool that, when the module is deployed, can be used to merge multiple modules into a single file, reducing the number of HTTP Requests.

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

Suppose you now have a math.js file that defines a math module. well, Math.js is going to write this:

Math.js

Define (function () {

var add = function (x, Y) {

Return x+y;

};

return {

Add:add
};

});

The loading method is as Follows:

Main.js

Require ([' math '], function (math) {

Alert (math.add ());

});

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 ([' mylib '], function (mylib) {

function Foo () {

Mylib.dosomething ();

}

return {

Foo:foo

};

});

When the Require () function loads the above module, the Mylib.js file is loaded First.

Vi. Loading of 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 '

}

}

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

I've been reading it for a while.

About modular personal Insights the so-called modularity is the independent scope of a statement && representation

Modular loading implements a couple of things

first, load JS file angle Rendering page angle to achieve && solve the problem

The first solution JS file loading too much cause page rendering too slow problem implementation file asynchronous loading

Second resolution JS compression internal code for too fast loading

second, JS file internal function of the modular angle

First solve the problem of pollution caused by global variables in JS file

The second resolution of unrelated files does not require loading problems to relieve server pressure

III. Modular notation

It's similar.

JavaScript Modular Programming

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.