Writing high-quality code: The way to develop the Web front-end (iii)

Source: Internet
Author: User

Chapter Fifth: High-quality JavaScript

This chapter of the content I see the longest, this is with my JS Foundation did not play good has a great relationship, but still resistant to read, do not understand the things are Baidu search, understand and then continue. Here are the notes recorded.

1) How to avoid JS conflict

A: anonymous function

When many people work on a website, everyone will write their own JS code, when defining variables may cause a naming conflict, how to avoid this conflict hidden trouble?

One of the simplest and most effective methods is that the anonymous function packages the script so that the scope of the variable is controlled within the anonymous function .

anonymous function: (function () {}) () The parentheses in the front are the body, followed by () to indicate execution.

such as: (function () {

var name,user= "Test"; The variables contained in this anonymous function are not window-scoped, but are confined inside the function. Because they are wrapped in different anonymous functions, they are no longer in conflict with each other.

})();

By using anonymous functions to package the script, we can control the global variables effectively and avoid the hidden conflicts.

B: Resolving communication problems between anonymous functions

The anonymous function above does resolve the conflict, but if you need to access each other's variables between two pieces of code, you are separated from each other and cannot access the variables in the other scope.

A better solution is to "define a global variable under the scope of window", but from the above conflict, the global variable is the killer that causes the conflict, if it is defined again, it violates the original intention of using anonymous function, so we should strictly control the number of global variables!

To control the number of global variables, hash objects are used as global variables.  var global={}; A variable of an object type as a global variable, good extensibility

After defining the object type variable, define the properties of the GLOBAL in anonymous function A: global.str1= "AAA"; The var B = blobal.str1 can be accessed directly in anonymous function B;

In this case, a problem arises when it also defines an attribute blobal.str1= "BBB" in the anonymous function B; At this point the attribute str1 in block A is overwritten. How to avoid this kind of conflict? It is not possible for each developer to find out which properties are bound before using the global object.

At this point, the namespace appears, it is a special prefix, in JS it is actually through a {} object to achieve. We can declare different namespaces for each anonymous function, and then the properties of the global object in each anonymous function do not hang directly on the global object, but are hung under the namespace of this anonymous function , both: Window Global. Namespace. A property variable that, when declared with the name of a property, does not cause a conflict even if the same name exists. such as: GLOBAL. a={};//defines a namespace, GLOBAL. A.str1= "AAA";//define attribute variables

Complex anonymous functions, you can also produce two-level namespaces, such as the global.a={};//level namespace, GLOBAL. a.cat={}; GLOBAL. a.dog={};//level two namespace;

Building a namespace is a common feature that can be encapsulated as a function.

var global={};

Global.namespace=function (str) {

var arr=str.split ("."), O=global;

For (i= (arr[0]== "GLOBAL")? 1:0; i<arr.length; i++) {

O[arr[i]]=o[arr[i] | | {};

O=o[arr[i]];

}

}

Call: Global.namespace (A.dog); Global.namespace (GLOBAL. B);

Summary: Solve the JS conflict-------namespace + global variable + anonymous function good combination to better resolve the conflict.

C: Comments

Adding the necessary code comments can greatly improve maintainability, which is important for team work.

Note The added information includes: function description, Engineer's name, contact details of the engineer, and the last modification time of the code;

So that JS does not conflict, you need to avoid the flooding of global variables, use namespaces appropriately, and add comments to the code.

2) JS Code Program Unified Entry---------Window.onload and Domready

JS is functionally divided into two parts: 1 framework (provided is the structure of the JS code, including the definition of global variables, namespaces, etc., and the specific application is not relevant, the part is included in each page)---base layer, common layer;

2 Application section (page function logic code snippet, different page has different function, different page application part of code also different)---page layer;

And the application part of the code is best wrapped in a well-agreed entry function, (the program uniform entrance, is for the JS application part of the), the general initialization of the part will be placed in a unified function init () {}, and then after the page fully loaded after the trigger;

Window.onload: Needs to be triggered when the page is fully loaded, including images, Flash and other rich media,

Domready: Just to determine whether all of the DOM nodes in the page have finished loading, he doesn't care if the content of the node is loaded or not.

so domready triggers faster than window.onload, which is more appropriate than window.onload to invoke the initialization function. "I generally use jquery, so the page will be loaded with $ (fuction () {...}"); or $ (document). Ready (function () {...}); 】

Another effect of simulating ready is to place the initialized JS code block in front of the body end tag, js ... </body>, which is loaded in order.

3) CSS placed in the page header, JS placed at the end of the page

Browser loading Web page, loading to JS, because the script is more, and the HTML code is not loaded, this is the page will show blank, the script blocked the loading of HTML, wait until the loading is not easy to complete, and sometimes found that these page elements have no style, so a good habit is that CSS put in the page header, JS placed at the end of the page (first load the CSS, then load the HTML, and then load JS.) This will be able to timely display the interface to the user, reduce the page blank time.

4) Introduce the concept of compilation---------file compression

JS compression is usually done by removing the space and wrapping, removing the comment, replacing the complex variable name with a simple variable name, the compressed JS file does become smaller, but the compressed file can not be re-compressed back to the original appearance.

Compression naming rules: Formerly known as. js compressed after the name: formerly-min.js

5) How JS layered----------(in order to make the code clearer, reduce redundancy, improve code reuse rate)

Same as CSS layering: Base layer: The lowest end, two responsibilities: 1: The difference between different browsers to provide a unified interface, 2: The extension of the JS language provided by the underlying interface, such as ToString ...

            The base layer provides an interface to the common layer and page layer.

Common layer: Provides reusable components that are independent of the specific functions in the page. The function of common layer is to be used for page layer;

Page layer: At the top, this layer is mainly to complete the functional requirements within each page.

A:base Layer

Trivial points of knowledge:

1:ie and FF get childnodes will not be the same, because FF will include blank, newline and other text information industry as a member of the childnodes, and IE will ignore it, only the DOM node as a member of the childnodes.

2:document.all is a property that is supported by IE, FF is not supported and can often be used to determine the type of browser.

3:nextsibling: Gets the next sibling node of a node.

A child node under a parent node, but the browser is not the same, in order to be compatible, it will do some processing according to the browser, the processing encapsulated into functions, such as such functions will be placed on the base layer. such as: Getnextnode (node)

4: Transparency: IE is implemented by filters, and FF is implemented via CSS's Opacity property. Node.style.filter= ' Alpha (opacity= ' 3 '); nodel.style.opacity=0.3;

The event object in 5:event:ie is the property of window, which is used for the global scope, and in FF, the event is present as the parameter of the events.

General function (e) {e=window.event| | e;} So e points to the event object under IE and ff.

Some of the property names of the event object are also different under IE and FF, such as "Object triggering event (label)" Accessed under IE via the Srcelement property, under FF via target

var element= e.srcelement | | E.target;

6: Bubble: Two overlapping tags click on one of the other, the other will also be triggered click events, JS will trigger the sub-container to listen to events, and then trigger the parent container listener event is called bubbling.

For business needs, we need to block event bubbling , implemented in IE by setting the Cancelbubble property of the event object to True, under FF, by invoking the Stoppropagation method of the event object.

if (document.all) {

E.cancelbubble=true;//ie

}else{

E.stoppropagation ();//ff

}

7:on, Attachevent and AddEventListener

When we define events, we tend to on** only once, and if we define them again, we will overwrite the previously defined methods. The most common is the OnClick event.

on*** 's listening style has no overlay effect, and the last defined on*** overwrites the previous event.

Attachevent (ie supported methods), AddEventListener (FF supported methods), they support the overlay of the listener handler function.

Example: Btn.attachevent ("onclick", function () {...}); Btn.addeventlistener ("click", Function () {...});

Summary: The above 1-7 points, in order to be compatible with different browsers and encapsulated some compatible processing functions, such as such functions will be placed on the base layer. such as: Getnextnode (node)

8: Extension of the JS language underlying interface

Example: Trim () Isnumber () isstring () Get () $ () extend () etc.

The base layer of JS and the page of the specific application logic is irrelevant, belong to the framework level.

B:common Layer

The common layer itself relies on the interface provided by the base layer, and the base layer code needs to be loaded first. It differs from the base layer: the common layer is not a simple interface, but rather a relatively large component. (such as setting and obtaining cookies, you can encapsulate the cookie component). It is related to the specific function, if the page does not need the relevant features, there is no need to load, and a good ease of use and scalability of the components, the code will be high, so the general common layer of JS to function as a separate file, such as Common_cookie.js,common_ Drag.js,common_tab.js.

The common layer of JS and the page in the specific application of logic independent, belong to the framework level.

C:page Layer

both the base layer and the common layer belong to the frame level, the page layer belongs to the application level, it can call the base layer interface and the components of the common layer

6) JS Class Library

It is common to have prototype. Dojo, Mootools,extjs,jquery,yui and so on. So much I use more is jquery, as if ExtJS is also good, later have time to study.

Reprint please indicate the source

Original address: http://www.cnblogs.com/Joans/archive/2012/09/12/2681550.html

Writing high-quality code: The way to develop the Web front-end (iii)

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.