Online Whitelist and Fallback Options

It is possible to force the browser to always access certain resources over the network (this process is known as whitelisting). This means the browser will not cache them locally and they will not be available when the user is offline. To specify a resource as online only, use the NETWORK: keyword (the trailing : is essential) in the manifest file like so:

CACHE MANIFEST index.html scripts/demo.js styles/screen.css

NETWORK: logĀ°.jpg

This whitelists logo.jpg by moving it into the NETWORK section of the manifest file. When the user is offline, the image will show up as a broken image link (Figure 6-1). When he is online, it will appear normally (Figure 6-2).

If you don't want offline users to see the broken image, use the FALLBACK keyword to specify a fallback resource like so:

CACHE MANIFEST index.html scripts/demo.js styles/screen.css

FALLBACK:

logo.jpg offline.jpg

Now, when the user is offline, he'll see offline.jpg (Figure 6-3), and when he's online, he'll see logo.jpg (Figure 6-4).

Figure 6-1. Whitelisted images will show up as broken links when the user is offline

Figure 6-2. Whitelisted images will show up normally when the user is online

Figure 6-3. Fallback images will show up when the user is offline

Figure 6-4. Hosted images will show up normally when the user is online

It's worth noting that you don't have to additionally list offline.jpg to the CACHE MANIFEST section. It will automatically be stored locally by virtue of being listed in the FALLBACK section of the manifest.

This becomes even more useful when you consider that you can specify a single fallback for multiple resources by using a partial path. Let's say I add an images directory to my website and put some files in it:

/demo.manifest

/index.html

/images/logo.jpg

/images/logo2.jpg

/images/offline.jpg

/scripts/demo.js

/styles/screen.css

I can now tell the browser to fall back to offline.jpg for anything contained in the images directory like so:

CACHE MANIFEST index.html scripts/demo.js styles/screen.css

FALLBACK:

images/ images/offline.jpg

Now, when the user is offline, he'll see offline.jpg (Figure 6-5), and when he's online, he'll see logo.jpg and logo2.jpg (Figure 6-6).

Whether you should add resources to the NETWORK or FALLBACK sections of the manifest file depends on the nature of your application. Keep in mind that the offline application cache is primarily intended to store apps locally on a device. It's not really meant to be used to decrease server load, increase performance, etc.

In most cases you should be listing all of the files required to run your app in the manifest file. If you have a lot of dynamic content and you are not sure how to reference it in the manifest, your app is probably not a good fit for the offline application cache and you might want to consider a different approach (e.g., a client-side database, perhaps).

0 0

Post a comment