HTML5 localStorage toolkit

HTML5 localStorage toolkit

HTML5 has brought with it 5mb of local storage for to make use of. What does this mean? It’s basically a key/value table where you can store persistent data. So you don’t have to keep loading it every browser request, or so you can visually show data instantly, and then verify it is still current via ajax and update the visual representation. Whatever the implementation, it’s a great thing and you should try to make use of it wherever possible.

BUT. There’s always a but. But, it’s still not supported by every browser, which is an annoyance. It’s very widely supported, so you don’t have to stress too much, but I’m going to share with you the code I use so I don’t have to do a check every time I want to store/call data.

Example 1 will check for localStorage support, and if it cannot find it then it will fake it. The faking doesn’t give you persistent storage, unfortunately, it just allows you to interact with it as if it were there so you don’t have to make extra calls.

 

Example 2 is a wrapper function I use to set/get values. The default functionality for localStorage does not support storing objects so if you want to store objects then we must convert them to a string first. This wrapper makes it easier for you, and still allow you to store normal values.

 

 

Dave

About David Parlevliet

Dave is long time developer with a passion toward teaching. He divides his time between his wife, her cat and his projects. He recently started using twitter so make sure to follow him!