Created
September 21, 2012 18:51
-
-
Save falcondai/3763201 to your computer and use it in GitHub Desktop.
Use Web Storage (or fallback to a JS object) to cache jsons for the async JSON method in d3js (http://d3js.org/).
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
// use HTML5 Web Storage or an object to cache | |
localStorage = localStorage || sessionStorage || {}; | |
sessionStorage = sessionStorage || {}; | |
// @param work: a function that works on k, i.e. of the form function(k) {} | |
// @param is_permanent: true if the data should be stored in localStorage, else in sessionStorage | |
function perform(work, k, url, is_permanent) { | |
var s = is_permanent? localStorage : sessionStorage; | |
if (s[k]) { | |
// data is in the storage | |
work(JSON.parse(s[k])); | |
} else { | |
// not cached, fetch the data from url | |
d3.json(url, function(json) {s[k] = JSON.stringify(json); work(json);}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment