O'Reilly logo

High Performance JavaScript by Nicholas C. Zakas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Ajax Performance Guidelines

Once you have selected the most appropriate data transmission technique and data format, you can start to consider other optimization techniques. These can be highly situational, so be sure that your application fits the profile before considering them.

Cache Data

The fastest Ajax request is one that you don’t have to make. There are two main ways of preventing an unnecessary request:

  • On the server side, set HTTP headers that ensure your response will be cached in the browser.

  • On the client side, store fetched data locally so that it doesn’t have be requested again.

The first technique is the easiest to set up and maintain, whereas the second gives you the highest degree of control.

Setting HTTP headers

If you want your Ajax responses to be cached by the browser, you must use GET to make the request. But simply using GET isn’t sufficient; you must also send the correct HTTP headers with the response. The Expires header tells the browser how long a response can be cached. The value is a date; after that date has passed, any requests for that URL will stop being delivered from cache and will instead be passed on to the server. Here is what an Expires header looks like:

Expires:    Mon, 28 Jul 2014 23:30:00 GMT

This particular Expires header tells the browser to cache this response until July 2014. This is called a far future Expires header, and it is useful for content that will never change, such as images or static data sets.

The date in an Expires header is a GMT ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required