5 Ways to Improve Your Ajax Performance
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 pageHTML, CSS, JavaScript, and various mediadoes 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.