Skip to content

Instantly share code, notes, and snippets.

@mauricesvay
Created December 10, 2010 21:53
Show Gist options
  • Save mauricesvay/736880 to your computer and use it in GitHub Desktop.
Save mauricesvay/736880 to your computer and use it in GitHub Desktop.
Abusing localStorage to build an aggressive cache
var assets = [
'http://localhost/offline-assets/fancybox/jquery.fancybox-1.3.4.js',
'http://localhost/offline-assets/fancybox/jquery.fancybox-1.3.4.css'
];
for (var i=0,l=assets.length; i<l; i++) {
loadAsset(assets[i]);
}
function loadAsset(url){
var asset = getCache(url);
if (asset.mimetype == 'text/css') {
var style = document.createElement('style');
style.type = asset.mimetype;
style.innerHTML = asset.data;
document.getElementsByTagName('head')[0].appendChild(style);
} else if (asset.mimetype == 'text/javascript') {
eval(asset.data);
}
}
function getCache(url) {
if (localStorage[url]) {
//in cache
return JSON.parse(localStorage[url]);
} else {
//not in cache, sync load
var data = '';
var asset = {};
$.ajax({
'async' : false,
'url' : url,
'success' : function(data, status, xhr) {
var header = xhr.getResponseHeader('Content-type');
var mimetype = 'text/plain';
if (header.indexOf('javascript') !== -1) {
mimetype = 'text/javascript';
} else if (header.indexOf('css') !== -1) {
mimetype = 'text/css';
}
asset = {
'mimetype' : mimetype,
'data' : data
}
localStorage[url] = JSON.stringify(asset);
}
});
return asset;
}
}
@mauricesvay
Copy link
Author

I know, sync load is stupid for performance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment