JavaScript DOM Programming Art (2nd edition) reading notes (5)

Source: Internet
Author: User

Best practices for smooth degradation

Visitors to the site are completely likely to use browsers that do not support JavaScript, and it is possible that the browser supports JavaScript, but the user has disabled it. If this is not the case, people who visit your website may encounter all kinds of problems and therefore no longer visit your website.

If you use JavaScript scripts correctly, you can allow visitors to navigate your site smoothly without JavaScript support in their browsers. This is known as a steady degradation, which means that although some functions are not available, the most basic operations can still be completed successfully.

Let's look at an example of opening a link in a new window:

function PopUp (winurl) {

window.open (Winurl, "popup", "width=320, height=480");

}

<a href= "#" onclick= "popUp (' http://www.example.com/'); return false; " >Example</a>

In this instance, the actual work is done by the onclick attribute and cannot be degraded smoothly.

In the link, set the href attribute to a real-world URL address, making it a valid link:

<a href= "http://www.example.com/" onclick= "popUp (' http://www.example.com/'); return false; " >Example</a>

Or

<a href= "http://www.example.com/" onclick= "PopUp (This.getattribute (' href ')"); return false; " >Example</a>

Or

<a href= "http://www.example.com/" onclick= "popUp (THIS.HREF); return false; " >Example</a>

All three of these methods are available.

This link is available even if JavaScript is disabled after the HREF attribute is set to a URL address that is actually present. Although this link has a bit of a feature discount (because it doesn't open a new window), it doesn't completely expire. This is a classic example of "smooth degradation".

The most obvious disadvantage of this technique is that you have to embed the JavaScript code in the markup document whenever you need to open a new window. This is a better technique if you can put all the JavaScript code, including the event handler, in an external file.

Learn from CSS

We often encounter Web documents with a style attribute for almost every element, and this is one of the most inefficient uses of CSS technology. The real way to benefit from CSS technology is to transfer all styles to an external file.

The separation of document structure and document style ensures that Web pages can be degraded smoothly.

The so-called "progressive enhancement" is the use of additional information layers to wrap the raw data. Almost all Web pages created in accordance with the "progressive enhancement" principle conform to the "smooth degradation" principle.

All the features that are similar to css,javascript and Dom should also form an additional layer of instruction. Similar to using the Style property, using attributes such as onclick in an HTML document is an inefficient and problematic practice. If we use a "hook", like the CSS mechanism of class or ID attributes, the JavaScript code call behavior and HTML document structure and content separated, the page will be much more robust. So how do you separate the JavaScript code from the example above?

<a href= "http://www.example.com/" class= "Popup" >Example</a>

Add an event to an element in an HTML document in an external JavaScript file:

Element.event = action ...

The key is how to determine the element that should get the event. The steps are as follows:

(1) Put all the links in the document into an array;

(2) traversing an array;

(3) If a link's class equals Popup, it means that the link should call the popup () function when clicked.

The following is the JavaScript code that implements the above steps:

var links = document.getElementsByTagName ("a");

for (Var i=0;i<links.length;i++) {

if (Links[i].getattribute ("class") = = = "Popup") {

Links[i].onclick = function () {

PopUp (This.getattribute ("href"));

return false;

}

}

}

There is one more problem to solve: if you put this code into an external JavaScript file, it will not work properly. Because the first line of this code is:

var links = document.getElementsByTagName ("a");

This statement will be executed as soon as the JavaScript file is loaded. If the JavaScript file is called from the

This code must be executed immediately after the HTML document has been loaded into the browser. Fortunately, an event is triggered when the HTML document is fully loaded, and the event has its own event handler function. I'll wrap my JavaScript code in the Preparelinks function and add this function to the OnLoad event of the Window object. In this way, the DOM will work as expected:

Window.onload = Preparelinks;

function Preparelinks () {

var links = document.getElementsByTagName ("a");

for (Var i=0;i<links.length;i++) {

if (Links[i].getattribute ("class") = = = "Popup") {

Links[i].onclick = function () {

PopUp (This.getattribute ("href"));

return false;

}

}

}

}

Don't forget to save the popup function in that external JavaScript file as well.

Backwards compatible

Your site's visitors probably don't have JavaScript enabled, and different browsers support JavaScript differently. Most browsers support JavaScript more or less, and most modern browsers support the DOM very well. But older browsers are likely to fail to understand the methods and properties provided by the DOM. Therefore, some scripts may not work correctly even if a user is using a JavaScript-enabled browser while accessing your website.

The simplest solution to this problem is to detect how much the browser supports JavaScript.

if (!getelementsbytagname | |!getelementbyid) return FALSE;

According to this idea, insert an if statement in the Web page load script used to add the onclick event to the link.

Window.onload = Preparelinks;

function Preparelinks () {

if (!document.getelementsbytagname) return false;

var links = document.getElementsByTagName ("a");

for (Var i=0;i<links.length;i++) {

if (Links[i].getattribute ("class") = = = "Popup") {

Links[i].onclick = function () {

PopUp (This.getattribute ("href"));

return false;

}

}

}

}

Although it is just an if statement, it ensures that those "old" browsers do not have problems with my scripting code. This is done so that the script has good backwards compatibility.

Browser sniffing technology

In JavaScript scripting code, it is not the only way to test whether a particular method or property exists before using it as the safest and most trusted way to ensure backward compatibility. In the crowded of the browser market, a technology called browser sniffing was once very popular.

"Browser sniffing" means resolving backward compatibility issues by extracting information from a browser vendor. In theory, information about the browser brand and version can be retrieved through JavaScript code, which can be used to improve backward compatibility of JavaScript scripting code, but this is a very risky technique.

First, browsers sometimes "lie". For historical reasons, some browsers will report themselves as a different browser, and some browsers allow users to modify this information arbitrarily.

Second, browser sniffing scripts can become more complex to apply to many different browsers. If you want browser sniffing scripts to work across platforms, you must test all possible combinations of vendor and version numbers. This is an endless task, the more combinations of tests, the more complex and lengthy the code is.

Finally, many browser sniffing scripts require the browser's version number to be matched exactly when doing such tests. As a result, these scripts have to be modified whenever a new version appears on the market.

Thankfully, the risky browser sniffing technology is being replaced by simpler and more robust object detection techniques.

Performance considerations

Minimize access to the DOM and minimize markup:

Whenever you query some elements in the DOM, the browser searches the entire DOM tree for possible matching elements;

In addition, too many unnecessary elements only increase the size of the DOM tree, increasing the time to traverse the DOM tree to find specific elements.

Merging and placing scripts:

Merging the scripts into a single script file reduces the number of requests that are sent when the page is loaded. Reducing the number of requests is usually the first consideration in performance optimization.

Putting the <script> tag somewhere else is not a problem, but putting all <script> tags at the end of the document,</body> the tag, you can make the page faster. Even so, when the script is loaded, the Load event of the Window object can still perform various operations on the document.

Compression script:

The so-called compression script, refers to the script file unnecessary bytes, such as spaces and comments, all deleted, so as to achieve the purpose of "compressed" file. Fortunately, there are many tools that can do it for you. Some refiners will even rewrite some of your code, using shorter variable names to reduce the overall file size. The streamlined code, while not easy to read, can drastically reduce file size. In most cases, you should have two versions, one working copy, you can modify the code and add comments, and the other is a thin copy for use on your site. In general, to separate from the non-lite version, it is best to add the min Word to the file name of the thin copy.

Here are a few representative code compression tools that are recommended for readers:

Douglas Crockford's Jsmin

Yahoo's Yui Compressor

Google's closure Compiler

JavaScript DOM Programming Art (2nd edition) reading notes (5)

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.