Created
November 23, 2021 14:29
-
-
Save langemike/4a18911469badba1b532d22a41294219 to your computer and use it in GitHub Desktop.
sessionstorage ajax request using jquery
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 getCache = function(cacheKey, expireMinutes) { | |
var value = sessionStorage.getItem(cacheKey); | |
var timestamp = Math.floor(Date.now() / 1000); | |
var expireTime = timestamp - (expireMinutes * 60); | |
var data = null; | |
if (value === null) { | |
return null; | |
} | |
data = JSON.parse(value); | |
if (typeof data !== 'object') { | |
return null; | |
} | |
if (data.created < expireTime) { | |
sessionStorage.removeItem(cacheKey); | |
return null; | |
} | |
return data; | |
}; | |
var setCache = function(cacheKey, value) { | |
var timestamp = Math.floor(Date.now() / 1000); | |
var data = { | |
value: value, | |
created: timestamp | |
}; | |
sessionStorage.setItem(cacheKey, JSON.stringify(data)); | |
} | |
var getData = function(url, cache) { | |
var cacheKey = 'cache_' + url; | |
var data = getCache(cacheKey, 15); | |
if (cache && data !== null) { | |
var d = $.Deferred(); | |
d.resolve(data.value); | |
return d.promise(); | |
} | |
return $.get(url).done(function(response) { | |
if (cache) { | |
setCache(cacheKey, response) | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment