Last active
September 27, 2018 15:47
-
-
Save nathansmith/9793648 to your computer and use it in GitHub Desktop.
Example of self-clearing cache using window.localStorage
This file contains hidden or 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
// Set up "namespace." | |
var APP = APP || {}; | |
// `Shared settings. | |
//---------------------------------------------------------------------------------------------------- | |
APP.config = APP.config || {}; | |
// How long to keep cache, in minutes. | |
APP.config.cache_duration = APP.config.cache_duration || 15; | |
// `Local storage cache. | |
//---------------------------------------------------------------------------------------------------- | |
APP.cache = APP.cache || (function($, window, document, undefined) { | |
// Strict mode. | |
'use strict'; | |
// Internal reference. | |
var cache = window.localStorage || {}; | |
var can_clear = typeof cache.clear === 'function'; | |
// What time is it? | |
var now = new Date().getTime(); | |
// When was it last updated? | |
var m = 60000; | |
var t = RWD.config.cache_duration * m; | |
var timestamp = cache.timestamp; | |
// Is the timestamp valid? | |
var invalid = !timestamp || now - timestamp > t; | |
if (invalid) { | |
// Flush the cache. | |
can_clear && cache.clear(); | |
// New timestamp. | |
cache.timestamp = now; | |
} | |
// Expose as "APP.cache" | |
return cache; | |
// Parameters: jQuery, window, document. | |
})(jQuery, this, this.document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.