Javascript - Local Storage with expiry options.

Most of the time, a local storage in HTML5 browsers is helpful to cache content from server for a certain period, Be it a dynamic menu, a big json data or a complex javascript object.

All it need is to store in local storage for a certain period, collect data from local storage without hitting server again and again. But when the caching time lapses, the content should be retrieved fresh from the server.

Below is a Javascript object which should be pretty much helpful to store and retrieve content in local storage with an optional time limit, expiring which, the returned value will be null instead, prompting us to get fresh data and store again.

Moreover, it saves javascript objects to localstorage, with a certain prefix to identify object ("_|_obj_|_"), so that it can parse the value at the time of storing and retrieving the object

var localStorageObj = {
    init: function () {
        this.$timeSuffix = "_lu";
        this.$expiryDuration = 100;
        this.$objIdentifier = "_|_obj_|_";
        if (typeof(Storage) !== "undefined") {
            hasLocalStorage = true;
        } else {
            hasLocalStorage = false;
        }
    },
    getCurrentTimeStamp: function () {
        if (!Date.now) {
            Date.now = function () {
                return new Date().getTime();
            }
        }
        return cTimeStamp = Date.now() / 1000 | 0;
    },
    setItem: function (key, item) {
        // Convert to string if the type of items is in object.
        if (typeof item === "object") {
            item = this.$objIdentifier + JSON.stringify(item);
        }
        if (!hasLocalStorage) {
            return false;
        }
        // set localStorage
        localStorage.setItem(key, item);
        // if track time store current time.
        localStorage.setItem(key + this.$timeSuffix, this.getCurrentTimeStamp());
    },
    getItem: function (key, expiryDuration) {
        if (!hasLocalStorage) {
            return false;
        }

        var data = localStorage.getItem(key);

        if (data == null) {
            return null;
        }
        // set default expiry duration if not provided.
        if (typeof(expiryDuration) === 'undefined') {
            expiryDuration = this.$expiryDuration;
        }
        // Check expiry.
        if ((this.getCurrentTimeStamp() - localStorage.getItem(key + this.$timeSuffix)) > expiryDuration) {
            return null;
        }

        return this.parseData(data);
    },
    parseData: function (data) {
        // parse data only if its meant to parse when set.
        if (data.substring(0, this.$objIdentifier.length) == this.$objIdentifier) {
            data = JSON.parse(data.substring(this.$objIdentifier.length));
        }
        return data;
    }
};
// Just initilize the object to set its local variables.
localStorageObj.init();


Now, how to use it? Our object has already been initialised in above script. We just need to check if value is available in a certain identifier (items). If data not available, call setItem() to store to localStorage in order to use it further. See below example :


1
2
3
4
5
6
7
8
var items = localStorageObj.getItem('items');
if (items === null) {
    // item not available in the localStoreage, collect it from elsewhere.
    items = {"key1" : "hello world", "another_key" : "This is another Value"};
    localStorageObj.setItem('items', items);
    // store for the first time. it will be available until cache time lapses.
}
console.log('items:', items);

Hope it helps!

Comments

Popular posts from this blog

Filtering and Sorting a Doctrine Arraycollection

Doctrine mapping (ORM) with Database (DAL), Unidirectional vs Bidirectional.

Drupal 7 - How to make dynamic select box through Drupal #ajax framework