80046

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

Question:

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

Answer1:

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); }); });

Answer2:

Another option is to override the $.ajax method. You can <a href="http://jsfiddle.net/st7C5/3/" rel="nofollow">try out my fiddle</a>. 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));

Recommend

  • jQuery - Wait for a function to return value
  • jquery ajax fails in firefox
  • Select onchange reload the page and keep the selected option
  • Localstorage clearing after app store update?
  • How to reload a page only once everytime it gets loaded
  • Google Adsense inside a jquery dialog?
  • Load in models dynamically in Laravel 5.1
  • How to subscribe on localStorage but not on sessionStorage events
  • R6010 abort() has been called
  • Backbone localstorage: Cannot read property 'Deferred' of undefined
  • Try to load image with Highgui.imread (OpenCV + Android)
  • From an action, get a post variable, output to page, then halt execution
  • Detect if user has closed ALL windows for a website?
  • Kill unload function in JS?
  • Program doesn't stop after exception
  • Canceling async httpwebrequests
  • Cannot read property setState of undefined in axios callback
  • Complete data loss Ionic / Cordova LocalStorage and Websql iOS 8.4.1
  • Angular2 How to display localStorage value inside HTML5 template?
  • How to keep button state across different pages?
  • C++ std::set comparator
  • How to autoplay video in angularjs?
  • Execute JavaScript code once a browser window/tab is opened for the first time
  • Doctrine2 bulk import try to work with another entity
  • Passing “get” parameters doesn't work, parameter not visible in the link
  • Angular2 Response for preflight is invalid (redirect) from some GET requests
  • Declaring variable dynamically in VB.net
  • GridView breaks while scrolling
  • Submit form in a displaytag pagination
  • 'TypeError' while using NSGA2 to solve Multi-objective prob. from pyopt-sparse in OpenMDAO
  • Can a Chrome extension content script make an jQuery AJAX request for an html file that is itself a
  • Circular dependency while pushing http interceptor
  • Matrix multiplication with MKL
  • AngularJs get employee from factory
  • NSLayoutConstraint that would pin a view to the bottom edge of a superview
  • How to set the response of a form post action to a iframe source?
  • Hits per day in Google Big Query
  • Change div Background jquery
  • File not found error Google Drive API
  • Converting MP3 duration time