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.)
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
- Plain text
- 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.
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.
- 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.