HTML and CSS Reference
In-Depth Information
Instead of using localStorage.setItem() and calling the object setter property di‐
rectly, with localStorage.small or localStorage['small'] , you can give your data
storage a 50% speed boost in Chrome ( Figure 6-1 ). The same performance test in the
latest Firefox and Safari web browsers, however, reveals that localStorage.setI
tem() performs better than the others for small values ( Figure 6-2 ).
As for most applications, you want your web app to perform at top speed across all
browsers. Usually, a real-world application will store a larger JSON object, base64 image
string, or HTML snippet in localStorage . As you can see with the largeValue tests in
the figures, all Storage API options perform roughly the same.
The StorageEvent API
Although Web Storage is considered to be “racy” (more on this in a moment), you can
avoid most race conditions by using the StorageEvent API. If the user has the same site
open in different tabs, this event can be used to synchronize the data. Here's a sample
usage:
window . addEventListener ( 'storage' , function ( evt ){ alert ( evt . key )}, false );
. key //returns the value of the key being changed. It's null upon creation.
. oldValue //represents the old value of the key being changed
. newValue //represents the new value of the key being changed
. url //the address of the document whose key changed
. storageArea //the Storage object which was affected. Either localStorage or sessionStorage
The storage event is fired only when the new value is not the same as the old value. The
storage event contains the key , oldValue , and newValue properties of data that has
changed, which you can access in code. This example creates the appropriate event
listener, which logs the oldValue and newValue across all open browser sessions:
window . addEventListener ( 'storage' , function ( event ) {
console . log ( 'The value for ' + event . key + ' was changed from' + event . oldValue
+ ' to ' + event . newValue );
}, false );
The storage event fires on the other windows only. It won't fire on the
window that did the storing.
What's Racy and What's Not?
Ultimately, a downside of Web Storage is the lack of transactions. For example, a user
might have your app open in two tabs. Tab 1 starts writing several things to the database,
then tab 2 starts reading it, getting the data when it has only partially been updated.
Search WWH ::




Custom Search