Last Updated: February 25, 2016
·
1.154K
· bunnymatic

In page cached jQuery Ajax queries

We have multiple Wysiwyg editors on the page which all pull a JSON list of images from the server that's used to populate an Image pick/insert function.

Though each element on the page is independent, we don't really want to fetch the image json individually. It'd be much nicer if we could cache it on the page.

I built this tiny jQuery ajax wrapper that caches the data on the page so the first call makes the request and saves the promise. Subsequent calls just get the promise back (from $.ajax) allowing multiple image pickers to get their data with only 1 ajax call.

Basically, instead of caching the data, we cache the promise.

window.CachedDataService = {

  inProgress: {
  },
  ajax: function(ajaxOptions) {
    var key = ajaxOptions.url + (JSON.stringify(ajaxOptions.data || ''))
    if (this.inProgress[key]) {
      return this.inProgress[key];
    }
    else {
      this.inProgress[key] = $.ajax(ajaxOptions);
      return this.inProgress[key];
    }
  }
}


/** sample call */

var ajaxOpts = {
  url: '/big_data_fetch'
}
var success = function(data) { 
  // do something with the data
}
var complete = function() {
  // do something after the fetch is finished
}

/* 
Try the following and watch your browser network tab. 
You should only see 1 XHR call.
*/

CachedDataService.ajax(ajaxOpts).done(success).always(complete)
CachedDataService.ajax(ajaxOpts).done(success).always(complete)

https://gist.github.com/bunnymatic/4cb28555860355660150