Publishers of technology books, eBooks, and videos for creative people

Home > Articles

5 Ways to Improve Your Ajax Performance

In sites that rely upon Ajax for functionality (or even pizzazz), performance becomes even more critical than the general JavaScript performance. Because Ajax requests take place behind the scenes, to the end user there is little discernible difference between an Ajax request being slow, and nothing happening at all. In this article, Larry Ullman explains some of the concrete steps you can take to improve the performance of your sites’ Ajax interactions.
Like this article? We recommend

Like this article? We recommend

Ajax is a fundamental tool in today’s web, and its usage has come to be expected, whether users are aware of it or not. Of course, the ideal is for users not to be aware of a page’s Ajax, as the ability to perform tasks without the user’s knowledge is one of Ajax’s benefits. But an Ajax process that executes slowly reflects poorly on the site (and on you, the developer).

Although there will be situations where that can’t be helped, I’ve come up with several steps you can take to minimize the potential for sluggish behavior and optimize the Ajax interactions.

Reduce the Number of Ajax Requests

For starters, the best performance can be had by not making an Ajax request at all. This may seem both obvious and pointless: dropping Ajax isn’t really better Ajax, is it? But there are ways you can have your Ajax cake and eat it too. The first goal isn’t to cut out all Ajax requests, but the unnecessary ones. Or, if you want to be aggressive, also cut the less necessary requests. If your script, for example, performs the same Ajax request every minute, see if every two minutes isn’t a reasonable alternative. If so, then you’ve just halved the number of requests!

With some Ajax processes, you may be able to cut requests drastically by changing when requests are made (as opposed to how often). For example, say you have a page in which the user can dynamically reorder a list of items. Offhand, you might be tempted to perform an Ajax request with each change in the order (presumably, the request would save the new order in the database). However, it’s likely the user would make multiple changes, resulting in multiple requests, and the fact is that it’s only the final order that really matters. One simple solution would be to add a submit button for the user to click and have the single Ajax request performed at that time. (To be safe, you’d probably want to add code that alerts the user should he or she attempt to leave the page after making changes without saving them.)

If you’d rather not leave it entirely up to the user, you could use JavaScript to watch for state changes and react accordingly. In this particular example, you could use an interval timer that makes the Ajax request every X seconds, but only if changes have been made since the last request. A simple flag variable can be used to watch for changes:

var changed = false;

You’d set that variable to true when a change is made. And a function executed every interval would then only perform the request if changed equals true. That function would also set changed equal to false again.

A third way to reduce the number of requests performed is to take advantage of browser caching. This only applies when Ajax is being used to request information, not when it’s being used to send data to the server.

The gist of caching is this: The browser will store local copies of site resources so that it won’t need to re-download them on subsequent requests (within a certain time frame). The browser’s attempts to cache resources also apply to Ajax requests made via the GET method (which can cause headaches during debugging). Thus, if your GET requests are cachable, you’ll improve the performance of the Ajax. Cache management is a bit of a higher-end subject, and often requires some server work to be done properly.

Use GET Requests When Appropriate

Speaking of GET request types, you should also know that GET requests tend to perform better than POST. To be fair, the decision as to which you use should mostly be based upon the particulars of the request:

  • GET requests are intended to retrieve information from the server.
  • POST requests are intended to cause a server reaction, such as the updating of a database record, the sending of an email, and so forth.

But GET requests are normally faster, so err on the side of overusing GET if there’s any question as to which is most appropriate.

Reduce the Amount of Data Transmitted

One benefit that Ajax brings to web pages is that they can minimize the amount of data that needs to be transferred back and forth between the client and the server. This is simply because the complete web page—HTML, CSS, JavaScript, and various media—does not need to be downloaded by the browser, and redrawn, just to confirm that a username is available or to fetch the latest stock quote. But the Ajax request itself can be written to send more or less data.

For starters, you can limit what actual data gets transmitted back to JavaScript by your server-side resource. Next, you should choose the best data format:

  • Plain text
  • JavaScript Object Notation (JSON)
  • eXtensible Markup Language (XML)

As with GET versus POST, there are other factors in selecting a data format, but do be aware that plain text will normally transmit the fewest bits of data, whereas XML can be verbose. Of course, JSON and XML are able to represent more complex data than plain text ever could, but don’t dismiss plain text as an option.

On a more advanced level, you can compress the data on the server before returning it. Modern browsers handle GZipped data well, although there is a trade-off in the extra processing required to GZip and unzip the data on either end. Transmitting GZipped data is a bit more advanced a concept, but one that should be on your radar.

Optimize the Server

If you have the ability to manipulate how your server runs, the performance of your Ajax requests can be improved by applying the same techniques used to improve the performance of any server request:

  • Have the server send the proper Expires or Cache-Control headers for the content being served.
  • Use ETags, which also direct caching behavior.

Neither of these solutions are difficult to implement, so if modifying your server’s behavior is an option, look online for more on using headers and ETags.

Another option, which doesn’t require changes to your server but does cost extra money, is to distribute your content over a Content Delivery Network (CDN). Doing so places resources geographically closer to users, thereby cutting the network transfer speeds. If the server-side Ajax resource is hosted on a CDN, users will benefit from that, too.

Improve the Performance of the JavaScript Code

Reducing the number of requests performed, and the amount of data included in both sides of the transaction, will have a dramatic impact on your Ajax performance. Making server changes will help, too, but may be beyond your control. Completely within your control are some code-based considerations you should be aware of. First, be vigilant about creating and destroying your XMLHttpRequest object at the optimal times.

For example, in Chapter 15, “PHP and JavaScript Together,” of my book Modern JavaScript: Develop and Design, I create an example based upon an auction site. The most complicated script in that chapter can perform two types of Ajax requests:

  • Submission of new auction bids
  • Retrieval of updated auction bids

If you think about this scenario, it’s easy to limit not only when requests are made, but also when the XMLHttpRequest objects themselves are created (each request uses a separate object). With this particular case, Ajax requests are only necessary if the auction is open, so code first checks for that condition. That check alone rules out all potential and unnecessary Ajax requests that would be made should any user view an expired auction.

Second, many users will view an auction but not bid on it, so the XMLHttpRequest object for performing bids is not initialized until the user submits a bid for the first time. This decision will improve the performance of the page in the user’s browser.

Both XMLHttpRequest objects are kept alive so long as the auction remains open. Both are destroyed as soon as the auction closes.

Beyond just the creation and destruction of the XMLHttpRequest objects, you should take a close look at the other JavaScript code in a page: If it performs poorly, it will undoubtedly impact the Ajax performance, and generally degrade the user experience. In particular, pay attention to how much Document Object Model (DOM) manipulation is involved, as DOM manipulation tends to be “expensive” in terms of performance.

Conclusion

Ajax is a vital tool in today’s dynamic websites, and its increased use is closely tied to JavaScript’s place as one of today’s most common and useful programming languages. But Ajax done poorly can be worse than not using Ajax at all. To minimize the potential for problems, and to create a more reliable user experience, incorporate the concrete suggestions outlined in this article into your next Ajax project.

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.peachpit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020