Last Updated: February 25, 2016
·
2.202K
· tadeuzagallo

Client- and Server-side caching with Javascript

Caching is a very common approach on server-side, but not so well explored on client-side (not talking about network or browser's native cache here...)

So a very common approach has became to cache requests, so you don't make it twice, you can even find it on jQuery examples page:

var cachedScriptPromises = {};
$.cachedGetScript = function( url, callback ) {
    if ( !cachedScriptPromises[ url ] ) {
        cachedScriptPromises[ url ] = $.Deferred(function( defer ) {
            $.getScript( url ).then( defer.resolve, defer.reject );
        }).promise();
    }
    return cachedScriptPromises[ url ].done( callback );
};

It is.... ok... but it doesn't give you any control over expiration, invalidation or persistence.

With this idea in mind, I write a Promise based cache library named stash.js (after the php library), that allows you to do some things like:

// reload the feed every 15 minutes
function getFeed() {
    return stash.get('feed').catch(function () {
        // cache not available
        return actuallyReachServer().then(function (serverData) {
            this.set(serverData, 15 * 60);
            return serverData;
        });
    });
}

And then:

getFeed().then(function (feedData) {
    document.querySelector('.feed').innerHTML = feedData;
}).done();

And of course you could use the exactly same approach on server (but reaching the database instead of the server...).

By now, Stash has 4 drivers: Ephemeral (in-memory cache), LocalStorage, Redis and Memcached. It is also multilayer, you can use any combination of drivers in any order you want that it will read top-down and write bottom-up. (IndexedDB driver is already on the way...)

Stash also comes with 4 invalidation strategies: NONE, OLD, PRECOMPUTE and VALUE.

If you are interested there is a very simple live demo consuming Facebook API available here and you can find even more on the project's github page