Created
February 14, 2017 13:59
-
-
Save rahmathm1/7f319a957b98a3eb4c2c7a8b38ffcc90 to your computer and use it in GitHub Desktop.
A snippet that load data from Ajax once the store it in session storage, then use it from session storage for future 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
/** | |
* 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