In the past few months, I’ve saw many developers that use local storage for ‘big data’ on the client side. Local storage is a powerful API that let developer save key-value data on the browser. However, it’s got some limitation like: synchronize operation that make it less efficient when it’s heavily used. Moreover, it should replace simple cases (e.g. saving the user state) and not in scenarios where you wish to save lots of data and then have the ability to ‘slide and dice’ it base on your needs with effiency. For that, we used to have WebSQL (which as you know is deprecated from 2010) and the new cool kid in town – IndexedDB. Here I will try to give you a short example that will run nicly both on IE10, Firefox (that match the spec) and Chrome (which need to tune a bit the setVersion update to call onupgrade). IE10 will support IndexedDB as well – so it’s great news to web developers in terms of ‘wild’ support for this important API in browsers. I wish we will see soon Safari (specially, on the mobile) match Chrome for android and give us the ability to leverage indexedDB both on Android and iOS.
Ok, as Linus said: “talking is cheap, show me some code”… Let’s go over the example code. In this example we will save todos to keep things simple. Classic, no? In the end of the post, I will also give two other examples of a ‘todo app’ the use indexedDB, WebSQL and jQueryMobile.
First let’s define our main variable and make sure we know how to handle all the browsers’ prefix.
Then we can run on the initialization of our stuff
In the above code you can see the interim solution for Chrome to create an objectStore for our todos. We could deprecated this code once it’s fixed and use this code:
Now we can hook up a listener to the button that will create a todo item for us. If you want to see the todos – just open Chrome DevTools and go to ‘Resources’ tab. There you can open the ‘todo’ DB under indexedDB item.
The full code: