HTML5 Tutorial – AppCache for Offline Apps

HTML5 Powered with Offline & Storage

You can create offline applications using the Application Cache API (or AppCache) that is defined in the HTML5 Specification.

AppCache enables webpages to cache (or save) resources locally, including images, script libraries, style sheets, and more. In addition, AppCache allows URLs to be served from cached content using standard Uniform Resource Identifier (URI) notation.

Appcache was intended to let your web app run offline, no Internet connection required, but it can also be used online to dramatically decrease load times.

The Problem and Solution

Let’s say we have a Web application that has an HTML page clock.html, a CSS style sheet clock.css, a JavaScript script clock.js. and a picture in images/clock.png.

If the user tries to open the clock.html page while offline the browser (unless it happens to have it still in the local cache) will fail with an error.

Instead, we can provide a manifest file that includes information about what files will be needed when your user is offline. A small file, that we might call clock.appcache, would have supplied the browser with a list of files to cache.

The first time the user went to your site, the HTML5 browser would render the page and display it, and then begin caching the files that are listed in the manifest.

Now, if the user goes to the page, the browser will cache the files and make them available even when the user is offline.

How to Cache Resources

To cache resources locally:

  1. Create a manifest file that defines the resources you want to save.
  2. Reference the manifest file in each webpage designed to use cached resources.

imageNOTE: You also need to set MIME-type in your for your .appcache file Web server so browsers will recognize the cache. See a following section for how to set the MIME-type in IIS.

Referencing the Manifest

Let’s start with the second step first, so you know how the manifest file is accessed.

You will point the browser to a file in the the manifest attribute of the html tag.

Here’s an example.


<!DOCTYPE html>
<html manifest="clock.appcache">
<head>
<title>Demo</title>
<script src="script/clock.js"></script>
<link rel="stylesheet" href="css/clock.css">
</head>
<body>
<img id="clockimg" src="images/clock.png" alt="clock" />
<p>The time is: <output id="clock"></output></p>
</body>
</html>

My simple manifest in a file named clock.appcache.


CACHE MANIFEST
script/clock.js
css/clock.css
images/clock.png

The Manifest

The manifest file is a text file that defines the caching behavior for resources used by the webpage.

You may want to have more control that simply caching some of the resources.

Note. You will find older examples that suggest that your manifest file should be called “cache.manifest“. Unfortunately, “.manifest” is already used by Microsoft, so you should recommendation is to use .appcache. (see HTML5 tracker, rev. 5812)

What Goes in the Manifest?

Manifest files can be divided into the following sections:

  • CACHE section lists all the resources that will be stored locally. The browser will begin downloading these in the background as soon as the page has loaded. If any are already in the browser’s cache, they will not be downloaded again separately.
  • NETWORK section lists the URLs that can be loaded when there is a network connection. Resources in this section are not cached. If your application includes any API calls, make sure to enumerate them here. Be sure to use the URL prefixes, like http:// or https://
    This section allows the use of the wildcard (*) character to indicate that all other resources should not be cached.
  • FALLBACK section defines resources to be used when other resources are not available.
  • SETTINGS specifies settings for appcache behavior. Currently, the only available setting is cache mode.

Note  File references in the manifest are interpreted with respect to the location of the manifest file, not the webpage that declares it.

Sample AppCache Manifest

The following is a sample of my manifest file:


CACHE MANIFEST
CACHE:
script/clock.js
css/clock.css
images/clock.png
FALLBACK:
*.png images/no.png
* offline.html
NETWORK:
online.html

view raw

sample.appcache

hosted with ❤ by GitHub

In this case, I moved the list of the items to be cached into the cache section.

In the fallback section, the code tells the browser that if it needs any .png file, then it should use no.png instead. And if any other is found that is not available, display offline.html.

In the network section, the never cache online.html file is never cached.

More about AppCache Manifest

Manifest files:

  • Must be encoded with 8-bit Unicode Transformation Format (UTF-8) character encoding.
  • Must be served with a text/cache-manifest MIME type.
  • Must begin with the line “CACHE MANIFEST”.
  • Can contain comments, preceded by the pound sign (#).

If any of the files mentioned in the CACHE section can’t be retrieved, the entire cache will be disregarded.

If the manifest file itself can’t be retrieved, the cache will ignored and all cached data associated with it will be disregarded.

The current page will be cached.

Programming the ApplicationCache Object

ApplicationCache object provides methods and properties for you to manage the application cache. In addition, you can define event handlers that show the progress of the cache process.

The ApplicationCache object supports the following events:

  • cached when the manifest has been cached.
  • checking when the presence of an update is being checked.
  • downloading when manifest resources are being downloaded.
  • progress while manifest resources are being downloaded.
  • error event occurs when a problem occurs, such as an HTML 404 or 410 response code. The event also occurs when the manifest file cannot be downloaded.
  • updateready event occurs when a newer version of the cache is available.
  • noupdate event occurs when an update has been request, but the manifest has not changed.
  • obsolete event occurs when the current cache is marked as obsolete.

The AppCache system always makes an attempt to request the manifest to check to see if it needs to update its list of assets. If that requests fails it is normally one of two things:

  • The manifest file is no longer being used (that is, it is not hosted) or
  • The system is unable to access the network to fetch the file.

Best Practices

Separate application logic from the application and use data.

  • List the logic (markup, scripts, style sheets, images, etc) in the manifest and stored in the application cache.
  • List a finite number of static HTML pages for the application.
  • Store the application and user data stored in Web Storage or a client-side Indexed Database.
  • Update the data dynamically using Web Sockets, XMLHttpRequest, server-sent events, or some other similar mechanism.

This model results in a fast experience for the user: the application immediately loads, and fresh data is obtained as fast as the network will allow it (possibly while stale data shows).

Any changes made to the manifest or any of its files will not take effect until the next page load. This is because once the page has been appcached, it is immediately served from that cache the next time the user returns.  The browser then checks the manifest for any changes and downloads any required files in the background. The newest version will be available on the next load of the page.

You can listen for the updateready event to detect this and prompt the user to reload the page:


if (window.applicationCache) {
applicationCache.addEventListener('updateready', function() {
if (confirm('An update is available. Reload now?')) {
window.location.reload();
}
});
}

Things to Know

Running Your AppCache in IIS

The manifest file has to be served with the mime type “text/cache-manifest“, otherwise the browsers will ignore it.

You can add a new mime type to IIS via the UI, command line, configuration files or WMI. See “Add a MIME Type“ on MSDN.

image

When you’re done, your MIME-type listing in IIS should look like this:

image

Setting Expiration of Your Files

You might want to adjust your settings so you are sure that the browser always gets the current manifest file. Otherwise you have no control over when the Offline Web application will be updated on the client.

You can configure this via UI, command line, configuration file or WMI.
(See documentation “Configure the HTTP Expires Response Header” on MSDN)

Running Mobile Boilerplate on Apache

imageIf you are running your web applications on an Apache web server, you might see about the pre-configured .htaccess file that comes with the HTML5 Mobile Boilerplate. Mobile Boilerplate helps you create rich, performant, and modern mobile web apps. Kick-start your project with dozens of mobile optimizations and helpers.

Resources

Sample Code

Sample code is available in the DevDays GitHub repository. See https://github.com/devdays/html5-tutorials