Cache AJAX results

Do not ask the server twice for the same data. Cache by URL and parameters.

jQuery · Cache AJAX resultsAdvanced
const cache = {};

function cachedGet(url, params) {
  const key = url + '?' + $.param(params || {});
  if (cache[key]) return $.Deferred().resolve(cache[key]).promise();

  return $.getJSON(url, params).done(function (data) { cache[key] = data; });
}

cachedGet('/api/cities', { country: 'pk' }).done(function (d) { console.log('first (network)', d); });
setTimeout(function () {
  cachedGet('/api/cities', { country: 'pk' }).done(function (d) { console.log('second (cache)', d); });
}, 100);
ajaxcachememoryperformance