Skip to content

Instantly share code, notes, and snippets.

@ferlores
Created August 15, 2012 03:47
Show Gist options
  • Save ferlores/3355635 to your computer and use it in GitHub Desktop.
Save ferlores/3355635 to your computer and use it in GitHub Desktop.
Overwrite jQuery ajax to cache repeated calls
var ajaxCache = {};
var oldAjax = $.ajax;
$.ajax = function(opts){
if (opts.type !== "GET") {
return oldAjax(opts);
}
if (ajaxCache[opts.url]) {
console.log('cached')
$.each(['success', 'error', 'complete'], function (index, method) {
if (opts[method]) {
ajaxCache[opts.url][method](opts[method])
}
});
return ajaxCache[opts.url];
} else {
console.log('make the call')
var p = ajaxCache[opts.url] = oldAjax(opts);
return p.always(function(){
delete ajaxCache[opts.url];
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment