How will caching be controlled

It's possible that an XMLHttpRequest response will be cached by the browser. Sometimes, that's what you want and sometimes it's not, so you need to exert some control over caching.

With cache control, we're talking about GET-based requests. Use GET for read-only queries and other request types for operations that affect server state. If you use POST to get information, that information usually won't be cached. Likewise, if you use GET to change state, you run the risk that the call won't always reach the server, because the browser will cache the call locally. There are other reasons to follow these this advice too; see RESTful Service (Chapter 9).

Often, you want to suppress caching in order to get the latest server information, in which case, a few techniques are relevant. Since browsers and servers vary, the standard advice is spread the net as wide as possible by combining some of these techniques:

• You can make the URL unique by appending a timestamp (http://www.howtoadvice.com/StopCachinq) (a random string, or a string from an incrementing sequence, is sometimes used too). It's a cheap trick, but surprisingly robust and portable:

var url = "sum.phtml?figure1=5&figure2=1&timestamp=" + new Date().getTime();

• You can add a header to the request:

xhReq.setRequestHeader("lf-Modified-Since", "Sat, 1 Jan 2005 00:00:00 GMT");

• In the Web Service set response headers to suppress caching (http://www.stridebird.com/articles/?showarticle=1&id=33). In PHP, for example:

header("Expires: Sat, 1 Jan 2005 00:00:00 GMT"); header("Last-Modified: ",gmdate( "D, d M Y H:i:s")."GMT"); header("Cache-Control: no-cache, must-revalidate"); header("Pragma: no-cache");

• Use POST instead of GET. Requests that are of POST type will sometimes cause caching to be suppressed. However, this particular technique is not recommended because, as explained in RESTful Service, GET and POST have particular connotations and shouldn't be treated as interchangeable. In any event, it won't always work, because it's possible some resources will actually cache POST responses.

On the other hand, caching is a good thing when the service is time-consuming and unlikely to have changed recently. To encourage caching, you can reverse the above advice; e.g., set the Expires headers to a suitable time in the future. In addition, a good approach for smaller data is to cache it in the program itself, using a JavaScript data structure. Browser-Side Cache (Chapter 13) explains how.

0 0

Post a comment

  • Receive news updates via email from this site