- Caching in HTTP
- Optimizing for mobile
- Using web storage
- The application cache
- Wrapping up
Using web storage
Browser makers, and Apple in particular, have left us with a less than ideal situation when it comes to the browser cache. But they and the W3C have given us something else that almost makes up for it: the web storage API. Web storage provides a persistent data store for the browser, in addition to cookies. Unlike cookies, 5 MB is available per domain in a simple key-value store. On iOS, WebStorage stores the text as a UTF-16 string, which means that each character takes twice as many bytes. So on iOS the total is actually 2.5 MB.
Using the web storage API
Web storage is accessed from two global variables: localStorage and sessionStorage. sessionStorage is a nonpersistent store; it’s cleared between browsing sessions. It also isn’t shared between tabs, so it’s better suited to temporary storage of application data rather than caching. Other than that, localStorage and sessionStorage are the same.
Just like cookies, web storage access is limited by the same origin policy (a web page can only access web storage values set from the same domain) and if users reset their browsers all the data will be lost. One other small issue is that in iOS 5, web views in apps stored their web storage data in the same small space used for the browser cache, so they were hardly persistent. This has been fixed in iOS 6.
The web storage API is very simple. The primary methods are localStorage.getItem('key'); localStorage.setItem('key', 'value'). key and value are stored as strings. If you try to set the value of a key to a non-string value it will use the JavaScript default toString method, so an object will just be replaced with [object object].
Additionally you can treat localStorage as a regular object and use square bracket notation:
var bird = localStorage['birdname']; localStorage['birdname'] = 'Gull';
Removing items is as simple as calling localStorage.removeItem('key'). If the key you specify doesn’t exist, removeItem will conveniently do nothing.
In addition to storing specific information, localStorage is a great tool for caching. In this next section, we’ll use the Flickr API to fetch a random photo for Birds of California, and use localStorage as a transparent caching layer to greatly improve the performance of the random image picker on future page loads.
Using web storage as a caching layer
For the Birds of California site, we can make things a little more exciting for users by incorporating a random image from Flickr, rather than a predefined image. This will sacrifice some of the gains we made in the last chapter in trimming images down to size, in exchange for developer convenience.
We’ll use the Flickr search API to find Creative Commons–licensed photos of birds. Listing 4.1 is a simple JavaScript Flickr API module that uses JSONP to fetch data. For the sake of brevity the code is not included here, but it’s available for download from the website. Let’s use this module to grab some images related to the California Gull.
Listing 4.1. Fetching the Flickr data
//a couple of convenience functions var $ = function(selector) { return document.querySelector(selector); }; var getEl = function(id) { return document.getElementById(id); }; var flickr = new Flickr(apikey); var photoList; flickr.makeRequest( 'flickr.photos.search', { text:'Larus californicus', extras:'url_z,owner_name', license:5, per_page:50 }, function(data) { photoList = data.photos.photo; updatePhoto(); } );
As you can see, the API takes a method (flickr.photos.search) and some parameters. This will hopefully give us back as many as 50 photos of Larus Californicus.
In Listing 4.2, the updatePhoto function takes the list, grabs a random photo from the list, and updates the image, the links, and the attribution.
Listing 4.2. Updating the photo
function updatePhoto() { var heroImg = document.querySelector('.hero-img'); //shorthand for "random member of this array" var thisPhoto = photoList[Math.floor(Math.random() * photoList.length)]; $('.hero-img').style.backgroundImage = 'url('+ thisPhoto.url_z + ')'; //update the link getEl('imglink').href = 'http://www.flickr.com/photos/' + thisPhoto.owner + '/'+ thisPhoto.id; //update attribution var attr = getEl('attribution'); attr.href = 'http://www.flickr.com/photos/' + thisPhoto.owner; attr.innerHTML = thisPhoto.ownername; }
Add this script (with the Flickr API module) to the Birds of California page with a valid Flickr API key and the bird hero image will dynamically update to a random option from the search results list. With no changes to the HTML and CSS from before, however, the user will see the original gull photo, and then a moment later it will be replaced with the result from the API. On one hand, this provides a fallback in case of JavaScript failure for the image. But on the other hand, it doesn’t look very nice, and we’ll go ahead and say the image is an enhancement to the main content, which is the text.
With that in mind, let’s create a null or “loading” state for the links and caption, as shown in Listing 4.3.
Listing 4.3. Hero image null state
<div class="hero-shot"> <a id="imglink" href="#"> <span class="hero-img"></span></a> <p class="caption"> Photo By <a id="attribution" href="#">...</a> </p> </div>
While the data is loading the user needs some indication that something’s happening, just so she knows things aren’t broken. Normally a spinner of some kind is called for, but in this case let’s just add the text “loading” and make the image background gray until it’s ready:
//show the user we are loading something.... var heroImgElement = $('.hero-img'); heroImgElement.style.background = '#ccc'; heroImgElement.innerHTML = '<p>Loading...</p>'; //Then inside updatePhoto I'll remove the loading state: heroImgElement.innerHTML = '';
So, now we have a pretty nice random image, with a loading state (Figure 4.1). However, we’re making users wait every time they visit for a random image from a list that probably doesn’t change that much. Not only that, but having a very up-to-date list of photos isn’t all that important because we just want to add variety, not give up-to-the-minute accurate search results. This is a prime candidate for caching.
Figure 4.1. The loading state.
If something is cacheable, it’s generally best to abstract away the caching, otherwise the main logic of the application will be cluttered with references to the cache, validation checks, and other logic not relevant to the task at hand. For this call we’ll create a new object to serve as a data access layer, so that rather than calling the Flickr API object directly, we’ll call the data layer, like so:
birdData.fetchPhotos('Larus californicus', function(photos) { photoList = photos; updatePhoto(); });
Because all we ever want to do is search for photos and get back a list, we can hide the Flickr-specific stuff inside this new API. Not only that, but by creating a clean API we can, in theory, change the data source later. If we decide that a different API produces better photo results, we can change the data layer without making changes to any consumers. In this case the key feature is caching. We want to cache API results locally for one day, so that the next time the user visits she’ll still get a random photo, but she won’t have to wait for a response from the Flickr API.
Creating the caching layer
The fetchPhotos method will first check if this search is cached, and whether the cached data is still valid. If the cache is available and valid, it will return the cached data, otherwise it will make a request to the API and then populate the cache after firing the callback.
First, we’ll set up a few variables, as shown in Listing 4.4.
Listing 4.4. A caching layer
window.birdData = {}; var memoryCache = {}; var CACHE_TTL = 86400000; //one day in seconds var CACHE_PREFIX = 'ti';
The memoryCache object is a place to cache things fetched from localStorage, so if those items are requested again in the same session they can be returned even faster; fetching data from localStorage is much slower than simply getting data from memory, without including the added cost of decoding a JSON string (remember, localStorage can only store strings). We’ll talk more about CACHE_PREFIX and CACHE_TTL shortly.
The first thing we need is a method to write values into cache. We’ll cache the response from the Flickr search, but wrap the cached value inside a different object so we can store a timestamp for a cache so that it can be expired.
function setCache(mykey, data) { var stamp, obj; stamp = Date.now(); obj = { date: stamp, data: data }; localStorage.setItem(CACHE_PREFIX + mykey, JSON.stringify(obj)); memoryCache[mykey] = obj; }
We’re using CACHE_PREFIX for each of the keys to eliminate the already small chance of collisions. It’s possible that another developer on the Birds of California site might decide to use localStorage, so just to be on the safe side we’ll prefix our keys. The date value contains a timestamp in seconds, which we can use later to check if the cache has expired. We’ll also add the value to the memory cache for quicker access to it if it’s fetched again during the same session. We’ll use the “setItem” notation for localStorage; this is much clearer than bracket notation—another developer will see right away what is happening, rather than thinking that this is a regular object.
The next function is getCached, which returns the cached data if it’s available and valid, or false if the cache is not present or expired (the caller really doesn’t need to know which):
//fetch cached date if available, //returns false if not (stale date is treated as unavailable) function getCached(mykey) { var key, obj; //prefixed keys to prevent //collisions in localStorage, not likely, but //a good practice key = CACHE_PREFIX + mykey; if(memoryCache[key]) { if(memoryCache[key].date - Date.now() > CACHE_TTL) { return false; } return memoryCache[key].data; } obj = localStorage.getItem(key); if(obj) { obj = JSON.parse(obj); if (Date.now() - obj.date > CACHE_TTL) { //cache is expired! let us purge that item localStorage.removeItem(key); delete(memoryCache[key]); return false; } memoryCache[key] = obj; return obj.data; } }
This function checks the cache in layers. It starts with the memory cache, because this is the fastest. Then it falls back to localStorage. If it finds the value in localStorage, then it makes sure to also put that value into the memoryCache before returning the data. If no cached value is found, or one of the cached values has expired, then the function returns false.
Next up is the actual fetchPhotos function that encapsulates the caching. All it has to do now is fetch the cached value for the query. If that value is false, then it executes the API method and caches the response. If it is true, then the callback function is called immediately with the cached value.
// function to fetch CC flickr photos, // given a search query. Results are cached for // one day function fetchPhotos(query, callback) { var flickr, cached; cached = getCached(query); if(cached) { callback(cached.photos.photo); } else { flickr = new Flickr(API_KEY); flickr.makeRequest( 'flickr.photos.search', {text:query, extras:'url_z,owner_name', license:5, per_page:50}, function(data) { callback(data.photos.photo); //set the cache after the //callback, so that it happens after //any UI updates that may be needed setCache(query, data); } ); } } window.birdData.fetchPhotos = fetchPhotos;
Now the data call is fully cacheable, with a simple API.
Managing localStorage
This is just the beginning for localStorage. Unlike the browser cache, localStorage gives you full manual control. You can decide what to put in, when to take it out, and when to expire it. Some websites (like Google) have actually used localStorage to cache JavaScript and CSS explicitly. It’s a powerful tool, so powerful that 5 MB starts to feel a little small sometimes. What do you do when the cache is full? How do you know if the cache is full?
First of all, we can treat localStorage as a normal JavaScript object, so JSON.stringify (localStorage) will return a JSON representation of localStorage. Then we can apply an old trick to figure out how many bytes that uses, including UTF-8 multi-byte characters: unescape(encodeURIcomponent('string')).length, which gives us the size of string in bytes. We know that 5 MB is 1024 * 1024 * 5 bytes, so the available space can be found with this:
1024 * 1024 * 5 - unescape(encodeURIComponent(JSON.stringify(localStorage))).length
If you want to know if you’ve run out of space, WebKit browsers, Opera mobile and Internet Explorer 10 for Windows Phone 8 will throw an exception if you’ve exceeded the available storage space; if you’re worried, you can wrap your setItem call in a try/catch block. When you’ve run out of storage you can either clear all the values your app has written with localStorage.clear, or keep a separate list in localStorage of all the data you cache and intelligently clear out old values.