Ajax returns multiple values: 5 ajax Best Practices

Source: Internet
Author: User
Tags format array object contains error handling html page json dojo toolkit

Guide: By learning 5 best practices, developers can apply them to day-to-day asynchronous JavaScript + XML (AJAX) development efforts. The article includes data format, error handling, and some Ajax-rich Internet Applications (RIAs) development tools. Mastering these best practices helps developers write more efficient and robust AJAX code.
The 5 best practices described in this article can be applied to Web application AJAX development efforts:
First, minimize calls
Second, let the data become smaller
Pre-loading components
Four, easy to implement error handling
V. Use of existing tools
These best practices help developers write more robust JavaScript code and make your AJAX code perform faster, which can benefit users.
Ajax overview
Ajax is used to describe technologies that have been in existence for a long time: JavaScript code, XML, and objects that can be called asynchronously over HTTP. Ajax is often used to avoid submitting and reloading the entire Web page, especially if the user does not need to reload the entire page.
In the past few years, AJAX-enabled sites are constantly improving, and as a development tool for such sites, Ajax applications are becoming more widespread. Use the practice of this article to build better Web applications with Ajax and JavaScript.
Minimize call
It may sound obvious, but using AJAX technology to improve Web application performance, the only thing you can do is minimize the number of calls.
One way to minimize the number of calls is to combine a large number of calls into small calls. If the amount of data is relatively small (see "Make data smaller"), then the main problem in most networks is latency. Latency is the time it takes for a browser to actually get a connection to a server and a service, sometimes it takes up most of the connection time. The total latency that a user feels is made up of several parts, including cache settings for browsers, DNS clients, and physical connections.
There is no simple formula or snippet for reading to learn how to reduce Web application calls. However, with just one simple exercise, you can demonstrate how to control the number of Ajax calls from the client to the server. Consider a Web application that buys second-hand motorcycles (see Figure 1).
Figure 1. Search for Second-hand Motorcycles sample Web page

First, the user chooses the year of the motorcycle. Then, the user chooses the construction of the motorcycle. The last user chooses the motorcycle model. From the beginning to the end, Ajax has been running in the background, updating the Drop-down box in the Web application to filter the list for users to make it easier for users to choose.
To start this exercise, first create a simple chart (with a text box) for the client and the server. Then draw a line of Ajax calls for the browser to get the user data from the server, as shown in Figure 2.
Figure 2. Drawing Ajax Calls

You can optimize the design by merging calls to the brand and model into one call. Instead of making a call to the brand and then making another call to the model, the model is cached so that when the user selects the brand, the new code retrieves only the list of models available in the cache. Fetching data from the local cache is much faster than getting the same data from the service. By avoiding additional service calls, developers can avoid delays in service invocation. The new communication situation is shown in Figure 3.
Figure 3. The Ajax call after merging the brand call and getting the model call

So far, the new design has removed a call 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 of which can be used to store data retrieved in an array for later use.
Listing 1. Storing local data in the cache
var choices = new Array ();

function fillchoiceboxes (year) {

Toolkit for links to Dojo ...
if (Dojo.indexof (choices, year) = =-1) {
Go get the
} else {
Make the AJAX call and fill the choices.
Choices[year] = result; Result of the AJAX call.
}

Calling a function to fill the values ...
Fillselect (Dojo.byid ("makes"), Choices[year]);

}
If a user considers two different models over and over again, the Web application uses local caching data instead of initiating additional service calls. Caching only static data-at least for the duration of the user session. Do not cause a series of problems by caching data that should not be cached.
As this example shows, the call can be minimized by reducing the number of interactions between the client and the server and, if possible, caching the data.
Make the array very small
To improve the performance of data processing, it is necessary to make the data transferred between the server and the client as small as possible. To perform this task efficiently, you must have control over the section from the service layer to the type of message that can be specified from the service to the client.
There is ample justification that XML is suitable as a common message format for clients to servers. One reason is that there are enough libraries or frameworks to use for XML serialization.
However, when contrasted with JavaScript serialized Object notation (JSON), XML appears verbose, while the former is more concise. There are already a lot of libraries that can easily be built into JSON format so that the client can pass data from the server side in a JSON way.
Many client libraries, such as Dojo Toolkit, allow you to define the transport format used by the service. If the service response uses JSON, you can use the same client object by providing a parameter.
Take a closer look at the code in Listing 2, which shows the representation of a motorcycle object that uses XML.
Listing 2. Motorcycle Data Using XML
<motorcycle>
<year>2010</year>
<make>Motocool</make>
<model>Uberfast</model>
</motorcycle>
Now take a look at listing 3, which shows the same data using JSON. Note that the amount of code in it is reduced by about 25% (if you remove spaces).
Listing 3. Motorcycle Data Using JSON
{
"Motorcycle": {
"Year": "2010",
"Make": "Motocool",
"Model": "Uberfast"
}
}
Because of the small number of data, not only reduces the transmission time from the server to the client, but also saves the parsing time because of the reduction of the string.
When you design the data that needs to be transferred, the less characters it contains, the better.
Pre-loading components
You can take advantage of browser caching by loading components such as JavaScript files and images in an Ajax call. It should be noted that the preload of JavaScript files and images is only beneficial to those who turn on caching, but most users ' browsers have caching enabled.
You want to preload an external JavaScript file to include the JavaScript file in the surface, but only if the page is small and you want to optimize only a small amount of resources, this approach is appropriate. For example, preloading is useful when you have a relatively lightweight page that introduces workflows to users. Consider the example of buying a motorcycle in the minimized call section. JavaScript code that contains all the AJAX code for the page containing the Drop-down box can be preloaded in the previous page of the stream.
If you want to update a picture with an Ajax-invoked method, preload the image provides great convenience. After the image is preloaded, you do not have to wait for the browser to retrieve the image when the user moves the mouse to the element, when the selection is made from the Drop-down box, or when the button is clicked. Even if Ajax occurs asynchronously, it will take some time to transfer images from the server to the client, and it will not be displayed on the client until the image has been fully downloaded.
In the example shown in Listing 4, when the user chooses a motorcycle from the list, the image used is preloaded with standard JavaScript code.
<body>
<!--Web Page ...-->
<script type= "Text/javascript" language= "JavaScript" >
var img = new Image ();
IMG.SRC = "Http://path/to/motocool.jpg";
</script>
</body>
The location of JavaScript is important when the image is preloaded for the page. Developers must not want to affect the loading speed of a page by adding JavaScript code to the HTML. The general rule is that the JavaScript code in the <script> element can be placed in the last part of the HTML page, because the browser has a relatively limited ability to consider 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 HTML5, you can use the new async property of the <script> tag. This tells the browser to run the JavaScript code asynchronously, so that it can be executed when something else is running on the page.
Easily handle Errors
Every function that is defined in JavaScript code assumes that malicious input will occur because the code that is strong in defense is better at handling errors than the code written with a catch statement. For example, if you want to use a JavaScript function to calculate based on user input, check the input before calculating, as shown in Listing 5. This article links http://www.cxybl.com/html/wyzz/JavaScript_Ajax/20121127/34435.html

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.