Writing high-quality code: Web Front-end development practices (3)

Source: Internet
Author: User
Tags blank page

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

 

Chapter 5: high-quality Javascript

I have read this chapter for the longest time. This is a great relationship with my Js foundation, but I am still able to read it. What I don't know is Baidu's search. After understanding it, I will continue. Below are the recorded notes.

1) how to avoid JS conflicts

A: anonymous Functions

When many people work together on a website, everyone will write their own JSCodeWhen defining variables, naming conflicts may occur. How can we avoid such conflicts?

The simplest and most effective method is"Anonymous function"Pack the script,Control the scope of variables within Anonymous functions..

Anonymous functions: (function () {}) () contains the function body in brackets, and () indicates execution.

For example: (function (){

VaR name, user = "test"; // variable contained in this anonymous function. The scope is not window, but within the function. Because their packages are in different anonymous functions, they do not conflict with each other.

})();

Using anonymous functions to pack scripts can effectively control global variables and avoid potential conflicts.

B: Solve the communication problem between anonymous functions.

The above anonymous function does solve the conflict, but if two code segments need to access each other's variables, they will be separated and cannot access the variables in the scope of the other party.

A better solution is to "define a global variable under the scope of window", but from the above conflict, global variables are the killer of conflicts. If so, this is against the original intention of using anonymous functions, so we should strictly control the number of global variables!

To control the number of global variables, the hash object is used as the global variable. VaR global ={}; // a variable of the object type is used as a global variable, which is highly scalable.

After defining the object type variables, define the global attribute in anonymous function A: Global. str1 = "AAA"; in anonymous function B, you can directly access var B = blobal. str1;

In this case, another problem occurs. In anonymous function B, it also defines an attribute blobal. str1 = "BBB"; in this case, the str1 attribute in block A is overwritten. how can we avoid such conflicts? It is impossible for every developer to find the attributes bound to the global object before using the Global object.

In this case, the namespace appears. It is a special prefix. In JS, it is actually implemented through a {} object. We can declare different namespaces for each anonymous function.Global Object AttributesBothDo not directly hookThe global object is stored in the namespace of the anonymous function., Namely:The global. namespace. Attribute variable in the window global. This way, when declaring the attribute name, the space will not conflict even if it has the same name. For example:Global. A ={}; // defines the namespace; Global. A. str1 = "AAA"; // defines attribute variables

In complex anonymous functions, you can also produce second-level namespaces, such as Global. A ={}; // Level 1 namespace, global. a. cat ={}; Global. a. dog ={}; // second-level namespace;

Generating a namespace is a common function 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: Solving JS conflicts ------- the combination of namespaces, global variables, and anonymous functions can better resolve conflicts.

C: Annotations

Adding necessary code comments can greatly improve maintainability, which is very important for teamwork.

The added information includes: function description, engineer name, engineer contact information, and last code modification time;

To prevent JS conflicts, we need to avoid the proliferation of global variables, reasonably use namespaces, and add comments to the code.

2) JS CodeProgramUnified portal --------- window. onload and domready

JS functions are divided into two parts: 1. Framework (it provides the organizational role for JS Code, including defining global variables and namespaces, and is irrelevant to specific applications, this part is included on every page) --- base layer, common layer;

2. Application Section (code segment of the page function logic. Different pages have different functions and different page application sections have different codes) --- page layer;

The application code is best packaged in an agreed entry function.JS Application SectionNormally, the initialization part will be placed in a unified function Init () {} and triggered after the page is fully loaded;

Window. onload: triggered only when the page is fully loaded, including rich media such as images and flash,

Domready: you only need to determine whether all DOM nodes on the page have been loaded. It does not matter whether the content of the nodes has been loaded.

Therefore, domready triggers faster than window. onload, which is more suitable for calling initialization functions than window. onload.[Jquery is generally used, so $ (fuction () {...}) will be used after the page is loaded (){...}); or $ (document ). ready (function (){...});]

AnotherSimulate ready resultsIs to put the initialized js code block in front of the body end tag JS... </body>, this will load in order.

3) Place CSS on the page header and JS on the end of the page

When a browser loads a webpage and loads it to JS, HTML code is not loaded because there are many scripts. This is a blank page and the script blocks HTML loading, when loading is not easy, sometimes the webpage elements do not have a style,So a good habit is,CSS is placed at the page header, JS is placed at the end of the page(Load CSS first, then HTML, and then Js .)In this way, the interface can be displayed to the user in a timely manner, reducing the page blank time.

4) introduce the concept of compilation ------- File compression

The common practice of JS compression is to remove spaces and line breaks, remove comments, and replace complex variable names with simple variable names. The compressed JS file does become smaller, however, the compressed file cannot be decompressed to restore it to its original form.

Compression naming rules: the name of the compressed. js file is-min. js.

5) How to layer JavaScript ---------- (to make the code clearer, reduce redundancy, and improve code reuse rate)

Same as CSS layering: base layer: the lowest-end. Two Responsibilities: 1. provide unified interfaces for JS differences between different browsers; 2. Extend the interfaces provided by the underlying JS language, for example, tostring...

The base layer provides interfaces for the common and page layers.

Common layer: Provides reusable components and has nothing to do with specific functions on the page. The functions of the common layer are used for the page layer;

Page layer: The top layer that meets the functional requirements of each page.

A: Base Layer

Trivial knowledge points:

1: Get childnodes in IE and FF will be different, because FF will include blank, line feed and other text information industry as a member of childnodes, and IE will ignore it, only use the DOM node as a member of childnodes.

2: Document. All is an attribute supported by IE. FF is not supported. It can also be used to determine the type of browser.

3: nextsibling: obtains the next peer node of a node.

Obtain the child nodes under a parent node. However, the browser is different. For compatibility, some processing will be made based on the browser, and the processing will be encapsulated into a function,Such functions will be placed on the base layer. For example, getnextnode (node)

4: Transparency: IE is implemented through the filter, and FF is implemented through the opacity attribute of CSS. Node. style. Filter = 'Alpha (opacity = '3') '; nodel. style. Opacity = 0.3;

5: Event: in IE, the event object is the property of window and acts on the global scope. In ff, the event exists as a parameter of the event.

Generally, function (e) {e = Window. Event | E;} // in this way, E points to the event object under IE and ff.

Some attribute names of the event object are also different under IE and ff. For example, "event triggering object (TAG)" is accessed through srcelement attribute in IE and accessed through target in ff.

VaR element = E. srcelement | e.tar get;

6: Bubble: When two overlapping labels click one, the other will be triggered. js will trigger the sub-container listening event first, the phenomenon of triggering the parent container listening event is called bubbling.

For business needs, we needPrevent event bubblesIn IE, you can set the cancelbubble attribute of the event object to true. In ff, you can call the stoppropagation method of the event object.

If (document. All ){

E. cancelbubble = true; // IE

} Else {

E. stoppropagation (); // FF

}

7: On, attachevent, and addeventlistener

When defining an event, we often can only define it once on **. If we define it again, it will overwrite the previously defined method. The most common event is the onclick event.

The on *** listening method has no overlapping effect. The last defined on *** overwrites the previous event.

Attachevent (methods supported by IE) and addeventlistener (methods supported by ff) support the superposition of listening processing functions.

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

Summary: Some compatible processing functions encapsulated to be compatible with different browsers in the above 1-7 periods,Such functions will be placed on the base layer. For example, getnextnode (node)

8: extensions of the underlying interfaces of the JS Language

For example, trim () isnumber () isstring () Get () $ () Extend () and so on

The JS at the base layer is irrelevant to the specific application logic on the page and belongs to the framework level.

B: common Layer

The common layer depends on the interfaces provided by the Base Layer. You need to load the base layer code first. The difference between it and the base layer is that the common layer is not a simple interface, but a relatively large component. (For example, you can encapsulate the cookie component by setting and obtaining the cookie ). it is related to specific functions. If the page does not require related functions, there is no need to load them. However, if a component with good usability and scalability, the amount of code will be high, therefore, JS on the common layer should be divided into separate files by function, such as common_cookie.js, common_drag.js, and common_tab.js.

JS on the common layer is irrelevant to the specific application logic on the page and belongs to the framework level.

C: Page Layer

Both the base layer and common layer belong to the framework level, and the page layer belongs to the application level. It can call the interfaces of the base layer and components of the common layer.

6) JS class library

Common examples include prototype. dojo, mootools, extjs, jquery, and Yui. I use jquery for so many times. It seems that extjs is also good, so I will be free to study later.

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.