New Feature: Playlist Center! Pick a topic and let our playlists guide the way.

Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Caching information with local storage

From: Mobile Web Design & Development Fundamentals

Video: Caching information with local storage

One of the features that native applications have always had is the ability to store information locally on the client, and in web applications that feature has usually been accomplished using cookies, but starting with HTML5 you can use a new feature called local storage, which provides persistent data storage without having to use cookies. Cookies have a few drawbacks associated with them. First, they are not very large; they're limited to about 4K of data.

Caching information with local storage

One of the features that native applications have always had is the ability to store information locally on the client, and in web applications that feature has usually been accomplished using cookies, but starting with HTML5 you can use a new feature called local storage, which provides persistent data storage without having to use cookies. Cookies have a few drawbacks associated with them. First, they are not very large; they're limited to about 4K of data.

Cookies are also transmitted to and from the server on every request, which bloats the request size and transmits data across the air needlessly, either incurring greater charges for the user or slowing down the experience. Cookies are also not very secure. They're sent as clear text unless your whole site is served as SSL. So those are some of the drawbacks of using cookies and local storage provides solutions to all these problems. First, it provides a much more database-like solution. The values that you want to store are stored per domain, just like cookies are, so other web pages can get at the information that you stored.

Data is stored as sets of key value pairs--again, sort of similar to how you do cookies and definitely the same way as you're probably used to using with associative arrays or objects. There is about 5MB of storage area for each domain to store data in, though currently no browser provides a way to increase that limit. And there is also a nice event model for detecting when changes take place in local storage. So in order to use local storage, you first have to detect if the local storage API is present in the browser.

You can do that one of a variety of ways. You can look for window.localstorage; in this example I am just using Modernizr. Modernizr, which we looked at earlier, is a way for detecting whether features are supported, and in this case I'm just using Modernizr to see if the local storage feature is present, and if it is, I can use that API to store data. Otherwise, there is no local storage, and in that case maybe I was fall back to using cookies. Once you've detected whether local storage is present, you can use it, and the local storage features are accessed from the window.local storage object.

So let's take a look at that API. To get and set items from and into local storage, you use the setItem and getItem methods. Or you can just use the bracket notation as if it were just an associative array, which you are probably used to using elsewhere in JavaScript. So right here you can see there is the setItem and I give it a key and I give it the value, and to get it back I just simply call getItem on the key, and here I'm using the associative-array way of doing this. Now one thing to note is that information that's stored in local storage is always stored as strings.

So if you store a number that's a pretty big floating-point number in local storage, each one of those numbers in that data is going to be stored as an individual character; it's not going to be stored as some 4-byte or 8-byte number. So you'll have to cast it back to being a floating-point number when you retrieve it later, because it going to come back as a string. To remove items from local storage and to clear out local storage entirely, you use the removeItem function and you give it a key, and removeItem will remove the data associated with that key. Or you can call the clear function, which will clear out local storage entirely.

You can also just retrieve general information about the local storage area. The localstorage.length property will tell you the number of key value pairs that are currently in storage, and you can also ask for the name of the key that's at index n. So if you want to iterate over all the keys and out what there names are, you can do that using the key function. Finally, let's take a look at handling local storage events. The local storage event object will send events up through the event model as changes happen to it, and the way that you do that is by using the addEventListener function to register a storage event and then give it the name of the function that you want to handle the events that happen on the local storage object. And when an event happens, the storage change handler here--well, that's what I've named it--will get called, and you can see what's going on.

The event object that gets passed into the event handler contains information about the storage change event. So in the event object there'll be these properties. There is key, there is oldValue, newValue, URL, and storageArea. The key is the name of the key that's been changed. It's either being added, it's being removed, or it's being changed in some way. The oldValue is the old value of the key, and if it's being added for the first time, this value will be null, because there is no old value. The newValue is the new value of the key.

The URL is the page that caused the storage area to change and the storageArea object refers to the storage object itself, your local storage or session storage. I didn't cover session storage in this section right here, but it works the same way as local storage does; it's just not saved out to disk. Let's take a look at some code to see how this actually works. So here we are in the code. This is my local storage example, and let me show you what its look in Design view, so you can see what we're going to do. What we're going to do is use this form to store some information locally on the client.

So I'm going to collect First Name, Last Name, and Postal Code and if we go back into the Source, you can see down here that's where the form is right here. And when that button gets clicked, we're going to call a function call storeLocalContent, and it's going to get the values of the first name, last name, and postcode input fields and store them locally. So what I'm going to do is fill out the code up here. To do that I'm going to my snippets file. So what I'm going to do is first copy this line, paste it in. And what this test is doing is seeing if the local storage object is present on the window.

Now I could have used Modernizr for this, but I thought it would be instructive to see how to test for the presence of local storage without using Modernizr. So it tests to see if there is a local storage property in the window object and if the window object's local storage property is not equal to null. So if that test evaluates to true, then we know that local storage is there. So I am going to copy this, and this line of code basically says that if local storage is not supported, then we're just going to replace the contents of the form with a little message that says, "Sorry, your browser doesn't support the storage API." Okay.

And then finally, I will copy the code that actually does the work, or does some of the work. If we load this page up and there is already some content in the local storage area, we're going to restore it into the form. So we're going to check to see it the local storage objects length is not equal to zero, which means there is always some key value pairs in there. And if there is data in there, we're going to get the information out of local storage and put it into the appropriate form field by last name, first, and postal code.

Okay, so let's save, and then I'm going to copy over my two functions for storing and clearing local content, and I'll paste those in right here. And this is the function that we're going to call when the user clicks on the Store Data button. So it is going to store the first, last name, and postal code. Okay, so I'll save, and we'll copy this over to our web server folder.

So let's first try this out in our Windows Phone emulator. So here's our form, and you can see that the contents of the form over there, so that means we support it. So I'm going to go ahead and type in my name. There's Joe, and I'll type in Marini, and my Postal Code is 90121, and now I'll click the Save button, and so now the data has been saved. So now if I were to navigate away from this page and now we go back to it, you can see that the data is being filled in again because the code that detected that there was information already in local storage is filling in the information.

Let's try it one other emulator to see if it works. Let's try it here in Opera, and here is the form. Let's go ahead and try it, and we'll save it, okay, and we'll navigate away from this. All right, and then we'll go back to it, and you can see that information is being filled in correctly. So using local storage, without using cookies, you can save information locally on the user's device in a persistent fashion and reload it as necessary.

Show transcript

This video is part of

Image for Mobile Web Design & Development Fundamentals
Mobile Web Design & Development Fundamentals

46 video lessons · 24017 viewers

Joe Marini
Author

 
Expand all | Collapse all
  1. 2m 48s
    1. Welcome
      1m 2s
    2. Using the exercise files
      1m 46s
  2. 29m 25s
    1. Understanding the mobile context
      8m 5s
    2. A survey of mobile sites
      11m 44s
    3. Targeting mobile browsers
      4m 31s
    4. Previewing a complete mobile site
      5m 5s
  3. 27m 20s
    1. Designing for one web
      3m 43s
    2. Using well-defined web standards
      3m 45s
    3. Designing mobile-friendly pages
      3m 40s
    4. Being crisp, clean, and succinct
      5m 45s
    5. Minimizing input where possible
      6m 47s
    6. Focusing on the core scenarios
      3m 40s
  4. 1h 13m
    1. Installing the tools
      3m 52s
    2. Setting up a local web server
      9m 13s
    3. Installing device emulators
      17m 5s
    4. Using device emulators
      13m 9s
    5. Downloading Modernizr and Mobile Boilerplate
      6m 22s
    6. Building a first mobile web page
      5m 43s
    7. Developing mobile pages with desktop browsers
      8m 6s
    8. Exploring useful mobile web development resources
      10m 23s
  5. 53m 26s
    1. Reviewing mobile markup languages
      5m 10s
    2. Understanding content adaptation approaches
      10m 32s
    3. Controlling the viewport layout
      12m 50s
    4. Designing forms
      13m 30s
    5. Using CSS media queries
      11m 24s
  6. 1h 11m
    1. Detecting client capabilities with script
      10m 8s
    2. Caching information with local storage
      9m 16s
    3. Determining position with geolocation
      12m 52s
    4. Minimizing HTTP requests with data URLs
      7m 39s
    5. Understanding user agent detection
      9m 8s
    6. Using server-side detection with PHP
      6m 52s
    7. Using server-side detection with ASP.NET
      4m 54s
    8. Using HTML5 Boilerplate for mobile
      11m 6s
  7. 39m 22s
    1. Measuring performance
      7m 41s
    2. Creating full-screen web apps
      6m 30s
    3. Customizing the user interface
      5m 14s
    4. Detecting orientation changes
      3m 58s
    5. Detecting device movement
      5m 21s
    6. Using touch events
      10m 38s
  8. 47m 14s
    1. Taking a look at the finished site
      7m 40s
    2. Examining the header and background image style on the Home page
      10m 10s
    3. Examining the hover effect and layout styles on the Tours page
      6m 42s
    4. Examining mobile forms on the Contact page
      9m 45s
    5. Viewing and testing the mobile site on emulators
      8m 11s
    6. Viewing the site on devices
      4m 46s
  9. 2m 34s
    1. Goodbye
      2m 34s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold

Are you sure you want to delete this note?

No

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.