Created
August 15, 2012 03:47
-
-
Save ferlores/3355635 to your computer and use it in GitHub Desktop.
Overwrite jQuery ajax to cache repeated calls
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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