Created
December 10, 2010 21:53
-
-
Save mauricesvay/736880 to your computer and use it in GitHub Desktop.
Abusing localStorage to build an aggressive cache
This file contains 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
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I know, sync load is stupid for performance.