logo
logo

Get in touch

Awesome Image Awesome Image

Development April 23, 2014

How To Handle Data Storage Problem with HTML5

Writen by Taeyaar Support

comments 0

Everyone active on the internet is aware of terms “online” as well as “offline”. There is a reason why both these terms are of great importance while working on the internet. In every individual’s life, there comes a time when they do not want to share their activities with the online world and hence they prefer to go offline. The best part about being offline is that they are still a part of the internet but the only difference is that they are no longer visible to other people.

Similar is the case with websites as well. No matter how huge or popular your website is, there will come a time during the establishment of your project when you will want to keep some data to yourself only. This means that you have uploaded data but you are not yet ready to share it with the world, hence you store that data offline. At times, it may be a result of some improvement or changes that you are bringing to your project. Earlier it used to be a tricky task to do this, but luckily, HTML5 has brought some really cool options so that you can store as well as handle data even in the offline mode.

What HTML5 has in store for you?

Looking at the need for offline data storage, HTML5 brought some really handy options, such as Local Storage, App Cache, Indexed DB and Session Storage. Each of these options are created to function in a specific manner and in this post below, I am going to discuss them one by one in detail.

Local Storage:

In case you want to store some data in the JavaScript code of your website, there can be no better option than using the Local Storage. Using this, you can conveniently store data without the need for entering any expiration date. This means that your data will securely remain inside the code for as long as you want to keep it there. The best part about using Local Storage is that if you are working within the same protocol as well as domain, you can access this stored data from any page on your website. What else do we need, right?

AppCache:

If you want to give your users the power to access some part of your website or the whole website without coming online on the server, you can simply use the App Cache option. By simply creating a file specifying what to cache and what not to cache, you can easily segregate your data. In case you have replacements for some of the files that have to be accessed only by going online, you can also specify them for your users. Use the following code to enable AppCache in HTML5 –

Define it –

<!DOCTYPEhtml>

<htmlmanifest=”manifest.appcache”>

</html>

Then define some static elements –

CACHE MANIFEST

CACHE:

/about.html

/portfolio.html

/portfolio_gallery/image_1.jpg

/portfolio_gallery/image_2.jpg

/info.html

/style.css

/main.js

/jquery.min.js

Be aware, you can’t use any wild card sign into AppCache declaration.

Now define fallbacks for content and comments and use * to stop all other resources from being cache –

FALLBACK:

/contact.html /offline.html

/comments.html /offline.html

NETWORK:

*

Indexed DB:

Using Indexed DB, you can easily store massive chunks of data in the user’s web browser. This is a great way of providing your users access to large documents as well as data without the need for any internet connection as well. All kinds of applications and websites, irrespective of their size, can use this option for easy data storage in the offline mode. First open the database and create the store –

// check if the indexedDB is supported

if(!window.indexedDB) {

    throw’IndexedDB is not supported!’; // of course replace that with some user-friendly notification

}

// variable which will hold the database connection

vardb;

// open the database

// first argument is database’s name, second is it’s version (I will talk about versions in a while)

varrequest = indexedDB.open(‘album’, 1);

request.onerror = function(e) {

    console.log(e);

};

// this will fire when the version of the database changes

request.onupgradeneeded = function(e) {

    // e.target.result holds the connection to database

    db = e.target.result;

    // create a store to hold the data

    // first argument is the store’s name, second is for options

    // here we specify the field that will serve as the key and also enable the automatic generation of keys with autoIncrement

    varobjectStore = db.createObjectStore(‘cds’, { keyPath: ‘id’, autoIncrement: true });

    // create an index to search cds by title

    // first argument is the index’s name, second is the field inthe value

    // in the last argument we specify other options, here we only state that the index is unique, because there can be only one album with specific title

    objectStore.createIndex(‘title’, ‘title’, { unique: true});

    // create an index to search cds by band

    // this one is not unique, since one band can have several albums

    objectStore.createIndex(‘band’, ‘band’, { unique: false});

};

Now use the following code to add and remove albums –

// adding

$(‘#add-album’).on(‘click’, function() {

    // create the transaction

    // first argument is a list of stores that will be used, second specifies the flag

    // since we want to add something we need write access, so we use readwrite flag

    vartransaction = db.transaction([ ‘cds’], ‘readwrite’);

    transaction.onerror = function(e) {

        console.log(e);

    };

    varvalue = { … }; // read from DOM

    // add the album to the store

    varrequest = transaction.objectStore(‘cds’).add(value);

    request.onsuccess = function(e) {

        // add the album to the UI, e.target.result is a key of the item that was added

    };

});

// removing

$(‘.remove-album’).on(‘click’, function() {

    vartransaction = db.transaction([ ‘cds’], ‘readwrite’);

    varrequest = transaction.objectStore(‘cds’).delete(/* some id got from DOM, converted to integer */);

    request.onsuccess = function() {

        // remove the album from UI

    }

});

And to display –

request.onsuccess = function(e) {

    if(!db) db = e.target.result;

    vartransaction = db.transaction([ ‘cds’]); // no flag since we are only reading

    varstore = transaction.objectStore(‘cds’);

    // open a cursor, which will get all the items from database

    store.openCursor().onsuccess = function(e) {

        varcursor = e.target.result;

        if(cursor) {

            varvalue = cursor.value;

            $(‘#albums-list tbody’).append(‘<tr><td>’+ value.title +'</td><td>’+ value.band +'</td><td>’+ value.genre +'</td><td>’+ value.year +'</td></tr>’);

            // move to the next item in the cursor

            cursor.continue();

        }

    };

}

Session Storage:

The functioning of Session Storage is similar to that of Local Storage. The only difference is that the data will be stored in the user’s web browser window only until he/ she closes it. Once this is done, all the data will be lost and no data is shared among the open windows/ tabs as well.

Using above techniques will help you to make enable your site offline to your viewers with improved speed and better data handling in HTML5. I hope you will implement any of these and get the better results from your HTML5 websites and blogs.