HTML and CSS Reference
In-Depth Information
you can do with localStorage , you can also do with sessionStorage and vice versa.
With sessionStorage , however, your data is stored only while that particular browser
window (or tab) is open. After the user closes the window, the data is purged. With
localStorage , your data will stay on the client across browser sessions, device restart,
and more. Any data stored is tied to the document origin, in that it's tied to the specific
protocol like HTTP or HTTPS, the top-level domain (for example ) , and the
port, usually port 80. One more caveat regarding sessionStorage : if the browser sup‐
ports resuming sessions after restart, then your sessionStorage object may be persisted
unknowingly. This can be an issue if your use case expects the sessionStorage data to
be destroyed upon closing of the browser.
Web Storage defines two APIs, Storage and StorageEvent, which either local or session
storage can use. This means you have two ways of working with and managing local
data. Whichever API you choose, remember with Web Storage, operations are syn‐
chronous: When you store or retrieve data, you are blocking the main UI thread, and
the rest of the page won't render until your data operations are finished.
The Storage API
As this usage example illustrates, the Storage API offers multiple ways of working with
your data in a storage object:
localStorage . bookName = 'HTML5 Architecture' ;
localStorage [ 'bookName' ] = 'HTML5 Architecture' ;
localStorage . setItem ( 'bookName' ) = 'HTML5 Architecture' ;
You can treat your data like any other JavaScript object and add the key directly as a
localStorage property, which calls setItem() behind the scenes. Your available func‐
tions are:
. length //returns the number of key/value pairs
. key ( n ) //returns the name of the nth key in the list
. getItem ( key ) //returns the current value associated with the key
. setItem ( key , value ) //creates new or adds to existing key
. removeItem ( key ) //you can probably guess what this does :)
. clear () //removes everything from storage associated with this domain
You might think that all of the methods for storing data have the same performance,
but that would be crazy talk in web browser land, right? Figure 6-1 and Figure 6-2 provide
a more realistic view and a performance analysis (
setitem-vs-getter-setter/4 ) on which storage approach works the best.
Search WWH ::

Custom Search