Collect the seven rules of non-abrupt JavaScript code on page 1/2

Source: Internet
Author: User

1. Do not make any assumptions
(JavaScript is an unreliable Assistant)
One of the most important features of JavaScript that may not be abrupt is-you have to stop any assumptions:
* Do not assume that JavaScript is available. You 'd better think it is probably unavailable, rather than relying on it directly.
* Before you test and confirm that some methods and attributes can be used, do not assume that the browser supports them.
* Do not assume that the HTML code is as correct as you think. Check every time and do nothing when it is unavailable.
* Make JavaScript Functions independent from input devices
* Remember that other scripts may affect your JavaScript Functions, so ensure that your script scope is as secure as possible.
Before designing your script, the first thing to consider is to check the HTML code for which you want to write the script and see what can help you achieve your goal.
2. Find the hook and node relationship
(HTML is the cornerstone of scripts)
Before writing a script, you should first look at the HTML for which you want to write JavaScript. If HTML is unorganized or unknown, it is almost impossible for you to have a good scripting solution-it is likely that the following situation will occur: either too many tags will be created using JavaScript, or the application is too dependent on JavaScript.
There are some things to consider in HTML, that is, the relationship between hooks and nodes.
<1>. HTML hook
The first and most important hooks of HTML are ID, and ID can be accessed through the fastest DOM method -- getElementById. If all the IDs in a valid HTML document are unique (there is a bug about name and ID in IE, but some good class libraries solve this problem ), using ID is safe, reliable, and easy to test.
Some other hooks are HTML elements and CSS classes. HTML elements can be accessed using the getElementsByTagName method. In most browsers, CSS classes cannot be accessed using the native DOM method. However, many external class libraries provide methods to access CSS class names (similar to getElementsByClassName.
<2>. HTML node relationship
Another interesting thing about HTML is the relationship between tags. Consider the following question:
* How can we easily reach the target node through the least DOM traversal?
* By modifying the tags, you can access as many subnodes as possible?
* What attributes or information can a given element be used to reach another element?
Traversing the DOM is resource-consuming and slow, which is why we should try to use the technology already in use in the browser to do this.
3. Hand over traversal to experts
(CSS, faster DOM traversal)
It seems interesting that many people are confused to traverse DOM scripts and usage methods or attributes (getElementsByTagName, nextSibling, previussibling, parentNode, and others. Interestingly, we have already done these things through another technology, CSS.
CSS is a technology that uses CSS selectors to traverse the DOM to access target elements and change their visual attributes. A complex JavaScript using DOM can be replaced by a CSS selector:
Copy codeThe Code is as follows:
Var n = document. getElementById ('nav ');
If (n ){
Var as = n. getElementsByTagName ('A ');
If (as. length> 0 ){
For (var I = 0; as [I]; I ++ ){
As [I]. style. color = '#369 ′;
As [I]. style. textDecoration = 'none ';
}
}
}
/* The following code is the same as the above function */
# Nav {
Color: #369;
Text-decoration: none;
}

This is a very powerful technique that can be used well. You can do this by dynamically adding a class to a high-level element in the DOM or changing the element ID. If you use DOM to add a CSS class to the document body, the designer can easily define the static and dynamic versions of the document.
JavaScript:
Copy codeThe Code is as follows:
Var dynamicClass = 'js ';
Var B = document. body;
B. className = B. className? B. className + 'js': 'js ';
CSS:
/* Static version */
# Nav {
....
}
/* Dynamic version */
Body. js # nav {
....
}

4. Understand browsers and users
(Create what you need in the existing usage mode)
An important part of Non-abrupt JavaScript is understanding how the browser works (especially how the browser crashes) and what the user expects. Without considering the browser, you can easily use JavaScript to create a completely different interface. You can drag the interface, fold the area, scroll bar, and slide block to create them using JavaScript. However, this is not a simple technical problem. You need to consider the following questions:
* Can this new interface be independent of the input device? If not, what can be relied on?
* Does the new interface I created follow the principles of browsers or other rich interfaces (Can you switch between them directly through the mouse in the multi-level menu? Or do I need to use the tab key ?)
* What functions do I need to provide, but does this function depend on JavaScript?
The last problem is actually not a problem, because you can use DOM to Create HTML out of thin air if needed. An example of this is the "print" link. Because the browser does not provide a non-JavaScript document printing function, you need to use DOM to create such links. Similarly, a title bar that enables the content module to expand and contract can also be clicked. The title bar cannot be activated by the keyboard, but the link is acceptable. To create a title bar that can be clicked, you need to use JavaScript to add the link. Then, all users who use the keyboard can contract and expand the content module.
An excellent resource for solving such problems is the design mode library. To know which items in the browser are independent from input devices, it is necessary to accumulate experience. The first thing you need to understand is the event processing mechanism.
5. Understand events
(Event processing will cause changes)
Event processing is the second step towards non-abrupt JavaScript. The focus is not to make everything drag, click, or add inline processing for them, but to understand that event processing is a completely isolated thing. We have separated HTML, CSS, and JavaScript, but we have not gone far in the separation of event processing.
The event processor monitors the changes in elements in the document. If an event occurs, the processor will find a wonderful object (usually a parameter named e ), this object will tell the element what happened and what it can do.
What really interesting about most event processing is that it not only happens to the elements you want to access, it also occurs on all elements at a higher level in the DOM (but not all events are like this, and the focus and blur events are exceptions ). For example, you can add only one event processor to a navigation list and use the event processor method to obtain the elements that actually trigger the event. This technology is called event delegation, which has the following advantages:
* You only need to check whether an element exists, instead of checking each element.
* You can dynamically add or delete subnodes without deleting the corresponding event processor.
* You can respond to the same event on different elements.
Another thing to remember is that when an event is propagated to a parent element, you can stop it and overwrite the default behavior of HTML elements (such as links. However, sometimes this is not a good idea, because browsers give HTML elements the behavior for a reason. For example, a link may point to a target on the page. without modifying them, you can add the current Script status of the page to the bookmarks.
6. Think for others
(Namespace, scope, and mode)
Your code is almost never the only script code in the document. Therefore, it is especially important to ensure that no other scripts can overwrite global functions or global variables in your code. There are some available modes to avoid this problem. The most basic point is to use the var keyword to initialize all variables. Suppose we have written the following script:
Copy codeThe Code is as follows:
Var nav = document. getElementById ('nav ');
Function init (){
// Do stuff
}
Function show (){
// Do stuff
}
Function reset (){
// Do stuff
}

The above code contains a global variable named nav and three functions named init, show, and reset respectively. All these functions can access the nav variable and access each other using the function name:
Copy codeThe Code is as follows:
Var nav = document. getElementById ('nav ');
Function init (){
Show ();
If (nav. className = 'show '){
Reset ();
}
// Do stuff
}
Function show (){
Var c = nav. className;
// Do stuff
}
Function reset (){
// Do stuff
}

You can encapsulate the code into an object to avoid the above type of global encoding, so that you can convert the function into a method in the object and change the global variable into an attribute in the object. You need to use the "name + colon" method to define methods and attributes, and add a comma after each attribute or method as the delimiter.
Copy codeThe Code is as follows:
Var myScript = {
Nav: document. getElementById ('nav '),
Init: function (){
// Do stuff
},
Show: function (){
// Do stuff
},
Reset: function (){
// Do stuff
}
}

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.