Skip to content

Ajax Cache Response jQuery Plugin

adamayres edited this page Feb 23, 2011 · 6 revisions

Ajax Cache Response jQuery Plugin

Overview

The Ajax Cache Response plugin caches the response of Ajax requests. Subsequent Ajax requests that match the original Ajax options will return the cached response instead of making a new call. Cached responses can be stored in a HTML5 web storage allowing them to persist across a session.

Why is this needed?

Typically Ajax requests are to made to URLs that provide dynamic content. These requests are usually configured to have expires headers in the past (or in the very near future). For most cases this is acceptable since we want to have fresh content. However there is some content that does not need to super fresh and using the Ajax Cache Response could save a round trip request to the server (and additional overhead of recreating the response).

Potential use cases

  • Tooltips that made Ajax requests to show previews of content on rollover
  • Ajaxified tabs that make a new Ajax request each time you goto a tab - perhaps within the same request this is not needed
  • Ajaxified search filters (the response for the same combination of filters could be cached)

Usage

The Ajax Cache Response plugin wraps the main jQuery.ajax(...) method. Usage of the plugin is done by adding a "cacheResponse" property to the jQuery Ajax options obejct and setting it to true.

jQuery.ajax("/my-ajax-url", {
	cacheResponse: true
});

An optional timer, in ms, can be set to control when the cache is invalidated. The timer will start after a successful Ajax request.

jQuery.ajax({
	cacheResponseTimer: 50000 
});

A optional function can be provided to invalidate the cache. A return value of false will invalidate the cache.

jQuery.ajax({
  	cacheResponseValid: function() { ... }
});

The storage for the cache respone is configurable. By default the cache is request scoped. Alternative storage options, that implement the HTML5 storage interface, can be used.

$.ajaxCacheResponse.storage = window.sessionStorage;

In order for the jQuery.get(...) and jQuery.post(...) methods to use the Ajax cached response the default Ajax options need to be changed to set the "cacheResponse" to true:

jQuery.ajaxSetup({
 	cacheResponse: true,
  	cacheResponseTimer: 50000, //optional
  	cacheResponseValid: function() { ... } //optional
});