Skip to content

Instantly share code, notes, and snippets.

@appastair
Last active January 4, 2016 00:29
Show Gist options
  • Save appastair/8541649 to your computer and use it in GitHub Desktop.
Save appastair/8541649 to your computer and use it in GitHub Desktop.
HTML5 localStorage AJAX Cache
function getTime(){
return ((new Date().valueOf() * 0.001)|0);
}
function cacheTime(key,time){
/* @TODO: Compare client/server cache ages! */
if((!window.localStorage.getItem('cache-ttl')) || !window.localStorage.getItem('cache-ttl').match(/(\{).+(\})/)){
var cacheTTL = {};
}
else{
var cacheTTL = JSON.parse(window.localStorage.getItem('cache-ttl'));
}
if(typeof(time)==='number'){
cacheTTL[key] = time;
window.localStorage.setItem('cache-ttl', JSON.stringify(cacheTTL));
}
return cacheTTL[key];
}
function dataCache(key, callback){
if(window.localStorage.getItem(key) === null){
$.ajax({
jsonpCallback: key
}).done(function(response){
cacheTime(key, getTime());
window.localStorage.setItem(key, JSON.stringify(response));
callback(response);
});
}
else{
if(!window.localStorage.getItem(key).match(/(\[).+(\])/) || (checkConnection() && (((getTime()-cacheTime(key)) > (60*15)) || !cacheTime(key)))){
cacheTime(key, 0);
window.localStorage.removeItem(key);
dataCache(key,callback);
return false;
}
var data = $.parseJSON(window.localStorage.getItem(key));
callback(data);
}
}
function checkConnection(){
$.ajax({
jsonpCallback: 'reachable'
}).success(function(reachable){
if(reachable){
window.localStorage.setItem('online', getTime());
}
return true;
}).error(function(){
window.localStorage.setItem('online','');
return false;
});
// return navigator.connection.type;
}
function loadTemplate(data){
var template = $("#template").html();
$("#template").html(_.template(template,{data: data}));
}
dataCache('data-key',loadTemplate);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment