Skip to content Skip to sidebar Skip to footer

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 loca

Solution 1:

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 requestif(!!window.localStorage && (key inlocalStorage)) {

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

        } else { // has not made this request// todo: determine which callbacks to interceptvar cb = options.success;
            options.success = function(responseText){
                localStorage[key] = responseText;
                cb.apply(this, arguments);
            };

            originalAjaxMethod.call( this, options );

        }
    };
}(jQuery));

Solution 2:

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]) returncomplete(cache[val]);

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

Post a Comment for "How To Create Custom Cache Mechanism For Ajax Calls Using Localstorage In Jquery?"