Nemo
Nemo

Reputation: 3164

How to create custom cache mechanism for ajax calls using localStorage in JQuery?

I was trying to write a custom caching mechanism for my ajax calls, which are mostly just data calls. So instead of putting them in the browser cache, I'm putting them down in localStorage for long term use.

But I cannot figure out how to fake request completion for JQuery.ajax. I can successfully intercept the call but my calls to the callback function do not have the same scope for some reason.

$.ajaxPrefilter(
 function( options, originalOptions, jqXHR ) {
  var key;
  originalOptions.data = originalOptions.data || {};
  key = options.localStorageKey = options.url + '?' + $.param(originalOptions.data);
  var value = localStorage.getItem(key);
  if(value)
  {
     //Still not working
    jqXHR.abort();//Abort this call
    options.success(JSON.parse(value));//Call the callback function
    return jqXHR();//return xhr for chaining (?)
  }
});

$('#logo').ajaxComplete(function(e,xhr,settings) {
//cache the request
  localStorage.setItem(settings.localStorageKey,xhr.responseText);
});

This does not work as intended. It does, sometimes, but there are scoping issues in the code. Is there any way I could actually fake the entire request ? So that the callback mechanism continues as it does. Something like

Request => Hook Ajax call (stop call, set response) => Continue ajax

Upvotes: 0

Views: 2833

Answers (2)

Josiah Ruddell
Josiah Ruddell

Reputation: 29831

Another option is to override the $.ajax method. You can try out my fiddle. Internally the $.ajax method is used for load, get, and post.

(function($){
    // Store a reference to the original ajax method.
    var originalAjaxMethod = $.ajax;

    // Define overriding method.
    $.ajax = function(options){
        var key = '';
        if(options.url)
            key += options.url;
        if(options.data)
            key += '?' + options.data;

        // has made this request
        if(!!window.localStorage && (key in localStorage)) {

            // todo: determine which callbacks to invoke
            var cb = options.complete || options.success;
            cb.call(this, localStorage[key]);

        } else { // has not made this request

            // todo: determine which callbacks to intercept
            var cb = options.success;
            options.success = function(responseText){
                localStorage[key] = responseText;
                cb.apply(this, arguments);
            };

            originalAjaxMethod.call( this, options );

        }
    };
}(jQuery));

Upvotes: 5

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

Maybe i'm wrong, but if i hit the cache i don't even start an ajax call. this is how i usually use cache, i think you can adapt it to use local storage instead of a cache object.

var cache = {};
var complete = function(data) {};

$("input").change(function(){
    var val = this.value;

    // key exists in cache-object, use it!
    if (cache[val]) return complete(cache[val]);

    // key doesn't exist yet, get the data an store it in cache.
    $.get(url, function(response){
          cache[val] = response;
          complete(response);
     });
});

Upvotes: 1

Related Questions