0

Is there a way to implement an app-wide in-memory cache for a HTML5 web application?

Is there a HTML5 feature to have in-memory cache of data? I'm not talking about the browser cache which merely stores server responses. I need caching of more efficient objects.

One possibility I can think of is to implement a global singleton JavaScript object that will be created once for the lifetime of the app, so that it can handle caching and retrieving data. If this is the only way, how can such a singleton object be created?

aligf
  • 2,020
  • 4
  • 19
  • 33
  • What's wrong with [`localStorage`](https://developer.mozilla.org/en/DOM/Storage#localStorage)? – Joseph Silber Mar 27 '12 at 14:37
  • A lot of HTML5 web applications are designed to be just one page that's updated with content as the application proceeds. – Pointy Mar 27 '12 at 14:38
  • Is `localStorage` saved on the disk or is it in-memory? Does it work for total data size of say 1 MB for mobile browsers? I couldn't find this information in the Mozilla link. – aligf Mar 27 '12 at 14:45
  • Here's a question and answer regarding the size limit of `localStorage` on iOS: http://stackoverflow.com/questions/1921048/limit-of-localstorage-on-iphone – Joseph Silber Mar 27 '12 at 14:48
  • For *much* more infornmation regarding `localStorage`, [read this](http://www.webdirections.org/blog/localstorage-perhaps-not-so-harmful/). – Joseph Silber Mar 27 '12 at 14:50
  • Thanks Joseph. But from the [link](http://www.webdirections.org/blog/localstorage-perhaps-not-so-harmful/) you sent, `localStorage` seems very slow and not fit for purpose of a robust cache. – aligf Mar 27 '12 at 15:04

1 Answers1

5

Here is a really simply singleton without too much enforcement. It could be done on a really protected way, where the Cache constructor isn't really accessible to the outer world, tell me if interested.

function Cache() {
     if ("instance" in arguments.callee)
       throw "new instance is not desired";
    var simpleCache = {};

     this.set = function(key, data) {
        simpleCache[key] = data;
     };

     this.get = function(key) {
       return simpleCache[key];
     };  
};

Object.defineProperty(Cache, "instance", { value: new Cache(), writable: false });

Now you call as you'd expect:

Cache.instance.set("key1", { a: "field1Value", b:12 });
Cache.instance.set("key2", new XMLHttpReuquest());
Peter Aron Zentai
  • 11,482
  • 5
  • 41
  • 71