# Simple cache mechanism?

In my system I frequently require data by Ajax requests. For example, different lists, content of modal dialogs, etc. This data can't be changed after request, so I wrote cache mechanism which stores Ajax result and then before Ajax request checks is there stored data. Here is example:

YFeX.cache = { }; // YFex is my own namespace

$('#account_modal_button').click(function () { if (YFeX.cache.account_modal !== undefined) { YFeX.modal(YFeX.cache.account_modal.title, YFeX.cache.account_modal.body); } else {$.ajax({
type:'GET',
context:$(this), success:function (data) { YFeX.cache.account_modal = data.modal; // YFeX.modal will be called automatically } }); } return false; });  Are there any 'bad' parts in my solution? • Not much to improve in just the couple of lines, but why not use browser's default caching? – JJJ Mar 10 '13 at 11:32 • @Juhana but Ajax request is executed in any case. – user0103 Mar 10 '13 at 11:43 • No, it isn't. That's the whole point of cache. – JJJ Mar 10 '13 at 15:22 • Doesn't jQuery already have a cache mechanism for it's AJAX functions? Adding cache : true should cache the response internally in jQuery. True, the AJAX routine still needs to be called. But if jQuery determines that there is cached data, probably it will not make a request and the response of the call will be from the cache. – Joseph Mar 10 '13 at 17:04 • @JosephtheDreamer I already tried set cache to true, but Firegug shows that Ajax request still sent. – user0103 Mar 10 '13 at 18:03 ## 1 Answer From a once over; • Unless YFeX is also a constructor, it should be yFex • lowerCamelCase is good for you: account_modal -> accountModal • I would store YFeX.cache.account_modal into a var cachedAccountModal so that you do not have to repeat YFeX.cache.account_modal all the time • Your code is very optimistic, you should also deal with fail • Consider using the shorthand $.get()
• Oh, after a year I see my own mistakes. But anyway thank you, it maybe helpful for someone... PS. account_modal means account[modal], I didn't want to create another arrays in cache array. – user0103 Apr 23 '14 at 10:20