Session storage is a very handy tool for caching content fragments retrieved via AJAX. Once we’ve pulled the content once, and stuffed it into session storage, we can access it again quickly without the overhead of a round trip to the server. But what if we want to limit the age of that content, so that it expires before it gets too stale?
A simple answer is to store the content with a timestamp, so that we know just how old it is. We can then compare that timestamp with the current time and see if the content is past its expiration time.
Of course, we can’t store JavaScript objects in session storage, only strings; luckily, we have JSON which is a string representation of JavaScript objects.
Here’s a JavaScript snippet that pulls content from the server via AJAX and saves it in session storage with a timestamp. On subsequent accesses, it gets the content from session storage, and if it hasn’t expired, it displays it straight away without having to go back to the server with AJAX again. Once the expiration time has been reached, the content is discarded and a new AJAX request is made.
/** * 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... }
Job is done the long way initially, kept in session storage until it’s too old, and refreshed again after that.