Skip to content

Instantly share code, notes, and snippets.

@Jamp
Created March 22, 2017 13:19
Show Gist options
  • Save Jamp/ef74696e027c4b5839b060db46689e6b to your computer and use it in GitHub Desktop.
Save Jamp/ef74696e027c4b5839b060db46689e6b to your computer and use it in GitHub Desktop.
Validar caducidad del sessionStorage
/**
* load the content via AJAX,
* and attempt to cache in sessionStorage
*/
(function() {
var hasStorage = ("sessionStorage" in window && window.sessionStorage),
storageKey = "yourUniqueStorageKey",
now, expiration, data = false;
try {
if (hasStorage) {
data = sessionStorage.getItem(storageKey);
if (data) {
// extract saved object from JSON encoded string
data = JSON.parse(data);
// calculate expiration time for content,
// to force periodic refresh after 30 minutes
now = new Date();
expiration = new Date(data.timestamp);
expiration.setMinutes(expiration.getMinutes() + 30);
// ditch the content if too old
if (now.getTime() > expiration.getTime()) {
data = false;
sessionStorage.removeItem(storageKey);
}
}
}
}
catch (e) {
data = false;
}
if (data) {
// load data from session storage
showContent(data.content);
}
else {
// fallback to AJAX loader
jQuery.ajax({
type : "GET",
url : your_ajax_url,
dataType : "html",
data : { action: "your-ajax-action" },
success : function(content, status, xhr) {
// save in session storage if available
if (hasStorage) {
try {
sessionStorage.setItem(storageKey, JSON.stringify({
timestamp: new Date(),
content: content
}));
}
catch (e) {
// silently suppress, it doesn't really matter
}
}
// show the new content
showContent(content);
}
});
}
})();
/**
* your function for displaying the content
* @param {String} content
*/
function showContent(content) {
// your code here...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment