alexfarrill / jquery-ajax-session-storage-cache

Cache jQuery ajax responses in html5 sessionStorage object with a ttl

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

jQuery Ajax Session Storage Cache

A simple, lightweight jQuery plugin for caching an ajax response in the html5 sessionStorage object (where available) with a ttl. Useful for reducing load on your servers for data that can be stale for an amount of time.

On the first request, an Ajax request is made with parameters you specify and the response is stored in the html5 sessionStorage object with a ttl. If there session storage is not supported by the browser, the request is performed as normal, but no cache is kept.

On a subsequent request if the cache still exists, the “success” callback you specify will be called with the cached data as the argument.

On a subsequent request if the cache is missing, the original ajax call will be made and response cached again.

The object’s representation in the sessionStorage object is a JSON string. For this reason, a JSON library that has methods “JSON.stringify” and “JSON.parse” must be included before loading. Works well with Douglas Crockford’s json2.js (github.com/douglascrockford/JSON-js).

Installation

Include script after the jQuery library (unless you are packaging scripts somehow else):

<script src="/path/to/jquery.ajax-session-storage-cache.js"></script>

Usage

$.ajax_session_storage_cache({
  key: "last_tweet",
  minutes_to_expiration: 60,
  ajax_options: {
    url: "/twitter.js",
    success: function(data) { $("#tweets").html(data); }
  }
});

Options

key: "last_tweet"

Name of the key to use for caching

minutes_to_expiration: 60

Number of minutes until cache should expire

Default: 5

ajax_options: { url: "/twitter.js", success: function(data) { $("#tweets").html(data); } }

An object passed to jQuery’s standard $.ajax method. See http://api.jquery.com/jQuery.ajax/

skip_cache: true or false

If true, Ajax request will happen each time. Useful e.g. if there is some subset of users (like admin users) who should never hit cache. Also a global option.

namespace: "my-app"

Namespaces the keys so you don’t have collision across applications, environments, deployments, etc. Also a global option.

Global Options

namespace:

see above

skip_cache:

see above

debug: true or false

Logs to the console object

e.g.

$.AjaxSessionStorageCache.options = {
  namespace: "development-myapp-deploy5859",
  debug: /^(development|dev_cache)$/.test(App.env),
  skip_cache: App.env === "development" || /admin=true/.test(document.cookie)
};

Changelog

Development

Author

Alex Farrill

About

Cache jQuery ajax responses in html5 sessionStorage object with a ttl


Languages

Language:JavaScript 100.0%