Last active
October 20, 2020 18:51
-
-
Save brynner/8226993 to your computer and use it in GitHub Desktop.
My solution to set a local cache with expiration, using HTML5 LocalStorage. This dramatically increases the performance of a mobile application.
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
/* Author: Brynner Ferreira (brynner.net) */ | |
// Functions | |
function removeHtmlStorage(name) { | |
localStorage.removeItem(name); | |
localStorage.removeItem(name+'_time'); | |
} | |
function setHtmlStorage(name, value, expires) { | |
if (expires==undefined || expires=='null') { var expires = 3600; } // default: 1h | |
var date = new Date(); | |
var schedule = Math.round((date.setSeconds(date.getSeconds()+expires))/1000); | |
localStorage.setItem(name, value); | |
localStorage.setItem(name+'_time', schedule); | |
} | |
function statusHtmlStorage(name) { | |
var date = new Date(); | |
var current = Math.round(+date/1000); | |
// Get Schedule | |
var stored_time = localStorage.getItem(name+'_time'); | |
if (stored_time==undefined || stored_time=='null') { var stored_time = 0; } | |
// Expired | |
if (stored_time < current) { | |
// Remove | |
removeHtmlStorage(name); | |
return 0; | |
} else { | |
return 1; | |
} | |
} | |
// Status | |
var cache_status = statusHtmlStorage('cache_name'); | |
// Has Data | |
if (cache_status == 1) { | |
// Get Cache | |
var data = localStorage.getItem('cache_name'); | |
alert(data); | |
// Expired or Empty Cache | |
} else { | |
// Get Data | |
var data = 'Pay in cash :)'; | |
alert(data); | |
// Set Cache (30 seconds) | |
if (cache) { setHtmlStorage('cache_name', data, 30); } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment