Five Ajax Best Practices

Source: Internet
Author: User
Tags representational state transfer dojo toolkit

The five best practices described in this article can be applied to your web application Ajax development work:

  • Minimal call
  • Reduce data
  • Preload Components
  • Easy error handling
  • Use existing tools

These best practices help you write more robust JavaScript code and make your Ajax code run faster, which can benefit users.

Ajax Overview

Ajax is used to describe existing technologies: JavaScript code, XML, and objects that can be asynchronously called through HTTP. Ajax is often used to avoid submitting and reloading the entire web page, especially when the user does not need to reload the entire web page.

Over the past few years, Ajax-supported websites have been constantly improved. As a development tool for such sites, Ajax has become more and more widely used. This article uses Ajax and JavaScript to build better Web applications.

Minimal call

It sounds obvious, but the only thing you can do to improve the performance of your Web applications using Ajax is to minimize the number of calls.

One way to minimize the number of calls is to merge a large number of calls into a small number of calls. If the data volume is relatively small (see "reduce data"), the main problem in most networks is latency. Latency is the time required by the browser to truly obtain the connection between the server and the service. Sometimes it takes most of the connection time. The total latency you experience consists of browser cache settings, DNS clients, and physical connections.

There are no simple formulas or code snippets for you to read to learn how to reduce web application calls. However, you only need a simple exercise to demonstrate how to control the number of Ajax calls from the client to the server. Consider buying a web application for a second-hand motorcycle (see figure 1 ).

Figure 1. Search the example web page of a used motorcycle

First, select the year of the motorcycle. Then, select the motorcycle structure. Finally, select the motorcycle model. From the beginning to the end, Ajax has been running in the background. Update the drop-down box in the Web application to filter the list for users so that users can choose from.

To start this exercise, you must first create a simple chart (with a text box) for the client and server ). Draw a line for the Ajax call made by your browser to obtain user data from the server, as shown in figure 2.

Figure 2. Draw an Ajax call

You can optimize the design by combining the call to the brand and model into one call. Instead of calling the brand once and then calling the model another time, the model is cached. In this way, when you select the brand, the new Code only retrieves the list of available models in the cache. Obtaining data from the local cache is much faster than getting the same data from the service. Avoid extra service calls to avoid service call delays. The new communication Condition 3 is shown.

Figure 3. Combined Ajax call after brand call and model call

So far, a new call has been removed from the communication between the browser and the server. You can use the code in Listing 1 to further reduce the number of calls. Some key lines can be used to store the data retrieved in the array for future search.

Listing 1. Storing local data in the cache

The following is a reference clip:
VaR choices = new array ();
Function fillchoiceboxes (year ){
// See resources for links to dojo toolkit...
If (Dojo. indexof (choices, year) =-1 ){
// Go get
} Else {
// Make the Ajax call and fill the choices.
Choices [year] = result; // result of Ajax call.
}
// Calling a function to fill the values...
Fillselect (Dojo. byid ('mak'), choices [year]);
}

If you repeatedly consider two different models, the Web application uses local cache data instead of initiating additional service calls. Only static data is cached-at least in the user session duration. Do not cause a series of problems because the data should not be cached is cached.

As shown in this example, you can minimize the call by reducing the number of interactions between the client and the server, and caching data whenever possible.

Make your array small

To improve data processing performance, we need to minimize the amount of data transmitted between the server and the client. To efficiently complete this task, you must have control over the part from the service layer to the Message type that can be specified from the service to the client.

There are good reasons to prove that XML is suitable as a common message format from the client to the server. One reason is that there are enough libraries or frameworks for XML serialization.

However, when compared with JavaScript serialized Object Notation (JSON), XML looks lengthy, and the former is more concise. Currently, many users can easily build your messages into a JSON library, so that you can transmit data from the server client in JSON mode.

Many client libraries, such as the dojo toolkit, allow you to define the transmission format used by the Service. If the service response uses JSON, you can provide a parameter to use the same client object.

Take a closer look at the code in Listing 2, which shows the representation of motorcycle objects using XML.

Listing 2. Motorcycle data using XML

The following is a reference clip:
<Motorcycle>
<Year> 2010 </year>
<Make> motocool </make>
<Model> uberfast </model>
</Motorcycle>

Now let's take a look at listing 3, which shows the same data using JSON. Note that the amount of code is reduced by about 25% (if spaces are removed ).

Listing 3. Motorcycle data using JSON

The following is a reference clip:
{
"Motorcycle ":{
"Year": "2010 ",
"Make": "motocool ",
"Model": "uberfast"
}
}

As the data size decreases, the transmission time from the server to the client is reduced, and the parsing time is also saved due to the decrease of the string.
  
When designing the data to be transmitted, the less characters it contains, the better.

Preload Components

The browser cache can be fully utilized by loading components such as JavaScript files and images in Ajax calls. It should be noted that the pre-loading of JavaScript files and images is only beneficial to those who enable the cache function, but most users' browsers have enabled the cache function.

To pre-load an external Javascript file, you can use this method only when the page is small and you only want to optimize a small amount of resources. For example, pre-loading is very useful when you have a relatively lightweight page that introduces workflows to users. Consider minimizing the number of motorcycle purchases in the call section. You can pre-load the JavaScript code that contains all the Ajax code on the page that contains the drop-down box in the early pages of the stream.

If you want to update an image by calling Ajax, It is very convenient to pre-load the image. After the image is preloaded, you do not have to wait for the browser to retrieve the image when you move the mouse to an element, select from the drop-down box, or click the button. Even if Ajax occurs asynchronously, it takes some time to transmit the image from the server to the client, and it will not be displayed on the client until all the images are downloaded.

In the example shown in Listing 4, when a user selects a motorcycle from the list, the image used is preloaded using standard JavaScript code.

Listing 4. Use standard JavaScript code to pre-load images

The following is a reference clip:
<HTML>
<Head> <title> preload example </title> <Body>
<! -- Web page... -->
<SCRIPT type = "text/JavaScript" Language = "JavaScript">
VaR IMG = new image ();
IMG. src = "http: // path/to/motocool.jpg ";
</SCRIPT>
</Body>
</Html>

When you pre-load images for pages, the Javascript location is very important. You do not want to affect the page loading speed because JavaScript code is added to HTML. The general rule is to put the JavaScript code in the <SCRIPT> element at the end of the HTML page, because the browser's capabilities are limited when considering how many resources can be downloaded at the same time. If possible, add the script to the last part of the HTML page to help the browser load images and other resources more quickly.

In HTML 5, you can use the new async attribute marked by <SCRIPT>. This tells the browser to run JavaScript code asynchronously so that it can run other things on the page.

Easy error handling

Every function defined in JavaScript code should assume that malicious input occurs, because the defensive code is better at handling errors than the code written using try... catch statements. For example, if you want to use JavaScript Functions for calculation based on user input, check the input before calculation, as shown in listing 5.

Listing 5. check user input

The following is a reference clip:
Function caculatedistance (source, DEST ){
If (! Isnan (source) |! Isnan (DEST )){
Dojo. byid ("errors"). innerhtml = "Please provide a valid number .";
}
}

Even if the code is defensive, you can use try... catch statements and error callback when appropriate. Listing 6 demonstrates how to use try... catch statements in JavaScript code to capture errors.

Listing 6. Use try... catch statements to handle errors

The following is a reference clip:
Function calculatedistance (source, DEST ){
Try {
// Do some calculations...
} Catch (error ){
Dojo. byid ("errors"). innerhtml = "An error occurred while adding the numbers ";

}
}

Listing 7 demonstrates the use of error callback when calling the xhrget () method provided in the dojo toolkit. The error parameter is optional, so it is easy to skip the definition of the error processor.

Listing 7. Use error callback with xhrget ()

The following is a reference clip:
VaR ARGs = {
URL: "/moin_static185/JS/dojo/trunk/dojo/../dojo/nosuchfile ",
Handleas: "text ",
Preventcache: True,
Load: function (data ){
// Do something when successful...
},
Error: function (error ){
Dojo. byid ("errors"). innerhtml = "An error occurred while getting the data ..";

}
}
VaR ajx = dojo. xhrget (ARGs );

How to handle errors on the page is both a business problem and a technical problem. Ask the customer what messages they want to see when a problem occurs, because any messages displayed to the user will affect the business. When appropriate, the customer can help provide effective default handling methods in case of exceptions.

Finally, do not display the error description in the Javascript prompt dialog box as in listing 8. Your user is not a software engineer, so such prompt information does not make any sense to the user. In addition to providing users with meaningless information, the prompt dialog box should ask customers to cancel the dialog box to return to the web page.

Listing 8. Avoid JavaScript prompt dialog box in error handling

The following is a reference clip:
Function calculatedistance (source, DEST ){
Try {
// Do some calculations...
} Catch (error ){
// Bad:
// Alert (error. Message );
// Better:
Dojo. byid ("errors"). innerhtml =
"An error occurred while calculating data ...";
}
}

Use existing tools

Finally, as one of the best practices, we should try to avoid the not supported Ted here (NIST) syndrome. Use existing tools (frameworks and platforms) to effectively use their resources. Most mature technicians use tools that have been tested on multiple platforms and have cross-browser compatibility. Most of the features of existing tools can be deployed in your own projects.

Many existing excellent tools not only provide Ajax calls, but also support many other functions and features, such as animation. Some of the tools are listed in Table 1.

Table 1. Javascript tools that provide methods for Ajax calls

Tools Description
Dojo Toolkit Dojo toolkit is a free JavaScript tool suite. It provides Ajax call methods and representational state transfer (rest) services for general web pages. The dojo toolkit method supports XML, JSON, and plaintext message formats.
Google Web Toolkit (GWT) designer Google recently acquired instantiations Developer Tools and released a series of free products. One of them is GWT designer, which can be installed in existing eclipse. The designer can be used to build interfaces using GWT. GWT is used to construct complex web applications using Ajax, which makes Web applications as complex as local applications. Similar to rich Ajax platform (RAP), GWT is not only a javascript framework, but also a Java-based tool set compiled into Ajax-enabled HTML.
Jquery Jquery is another JavaScript library that provides a full set of Ajax functions. Jquery also supports different message formats and other Ajax-based methods, such as getscript (), which can be used to download and execute JavaScript files (which is the origin of the best practices for preload components ).
Prototype Prototype is also a javascript framework that can be used to conveniently initiate Ajax calls. Using methods such as Ajax. periodicalupdater, you can update the values on the Ajax page based on the policy. In this way, you can control the progress bar or other methods for long-running service processes.
Rich Ajax platform (RAP) Unlike other frameworks listed in the table, rap is a complete platform that allows you to use eclipse integrated development environment (IDE) and Java (not scripts) code to build a better site with Ajax-enabled. It is similar to building a swing or Standard Widget Toolkit (SWT) application. For Java programmers who do not want to use complex HTML, CSS, and JavaScript code, rap and other platform tools are very good choices.

The RAP document prompts you not to install it as a plug-in to existing eclipse. However, you can download the eclipse for rich client platform (RCP) and rap developers packages from the eclipse site and install them in a separate location. The related memo list shows how to import the sample project.

Conclusion

Using ajax in Web applications provides a clean web application interface for your users. Ajax has provided some optimizations for the delivery of the entire HTML page. However, by understanding the best practices described in this article, you can build more optimized Ajax applications.

Collection: http://www.searchsoa.com.cn/showcontent_54832.htm

Related Article

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.