Friday, October 02, 2009

Offline Storage with Safari (Offline iPhone Webapps)

Resources can have 3 states

You can think of every resource as being assigned one of the following 3 states by Safari based on your manifest: missing, cached, online. Cached resources are stored in the Safari store; Safari can display cached resources when offline. Online resources will be retrieved from the server when offline (sometimes also called white listed). Finally missing means that the resource is not in the cache and that Safari won't try to get it from the cache when offline, so loading that resource will fail.

How states are assigned

If the HTML links to a manifest, by default the HTML is cached and all the other resources are missing. So you need to include every resource used by your page in the manifest to either tell Safari that it can be cached (images, CSS...), or that it should need to establish a connection to a server (end-points for Ajax requests).

Checking the state of resources

To see what state Safari assigned to your resources, open the Web Inspector, go to the Resources tab, and switch to the view by Time. Resources that are missing will show in gray. It is harder to see the difference between resources that are cached and online. Most likely you'll notice that online resources take a longer time, and of course you can check your server log to see if a resource is loaded as you reload the page. For missing resources, you can also open the Activity window (from the Window menu); Safari will show a message in red "The URL can't be shown" next to missing resources.

Checking if caching is happening

You can check if any caching at all is happening by looking at the value of window.applicationCache.status. In general the value will be 0 (UNCACHED) if the page isn't cached and 1 (IDLE) if it is.

The text/cache-manifest content type

What they the spec says about the text/cache-manifest content type isn't a joke ;). Make sure that your manifest is served with the appropriate content type, or it will be ignored.

Same site policy for the manifest

You need to serve the manifest from the same site from which the page is served. If you link to a manifest on another server, Safari will just ignore it. In the manifest itself, you can however list resources loaded from other sites that you would like to be cached, for instance libraries you load from the Google CDN.