Build an HTML5 Offline Application with Application Cache, Web Storage and ASP.NET MVC
The modern web ecosystem is made up of many different types of scenarios of how users interact with online content. With the increasing popularity of mobile devices along with countless hours at Starbucks and on airplanes, users may often find themselves in a position of wanting to use web content while not being able to enjoy reliable and continual access to the Internet.
A website that is not configured to operate in a disconnected state is unavailable in any form if an Internet connection is not available. For instance, Figure 1 demonstrates the type of response you may encounter while trying to view http://msn.com while working without an Internet connection.
Figure 1: Undesireable results often occur when a user attepts to load a web page when a connection to the Internet is not available.
Fortunately “offline web applications” continue to work for users regardless of Internet connection status to the client. The availability is possible by the new HTML Offline Web Application API (http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html), also known as HTML Application Cache. An offline application is a packaged group of web pages, style sheets, and/or scripts files that are reliably available to the client whether or not a web connection is present.
Offline web applications are available through the new HTML Offline Web Application API, also known as HTML Application Cache.
Beyond simply serving pages to the user when an Internet connection is unavailable, often an offline application requires storage of user’s information. HTML Web Storage is able to store relatively large amounts of information on the client giving you the ability to save data locally and synchronize with the server as a connection to the web becomes available.
The example in this article uses the Application Cache and Web Storage APIs together to build an application that works offline to store user information and automatically synchronize with the server when available.
What Is the Application Cache?
As stated above, an offline application is a packaged group of web pages, style sheets and/or scripts files that are saved on the user’s machine in the application cache. When a request for a file from the application is initiated, instead of requesting the file from the web server, the file is served from the application cache. In order to keep the application packaged and versioned correctly, a file called the application manifest maintains a master list of files in the application. When connected to the web, the manifest is checked for updates and any new versions of the application’s files are downloaded in the background for the next visit to the page.
Pages loaded into the application cache are served from the cache whether or not a connection to the Internet is available.
As with any new web technology, the question of browser support is often a determining factor for widespread use by web developers. The good news is that the latest versions of the mobile web browsers support offline applications along with some very early releases of many desktop browsers. Unfortunately, Internet Explorer support is not scheduled until the release of version 10. Table 1 details the browser support for offline applications for a wide array of desktop and mobile browsers.
Anatomy of an Offline Application
There are a number of elements working in concert that enable an offline application to operate as intended. To get a quick understanding of the files, features and APIs involved in creating an offline application, review the different building blocks listed in Table 2. Each of the elements described in Table 2 play a crucial role in serving, enabling and maintaining offline applications.
Understanding Cache Manifest
The application manifest file acts as the master list of files for the offline application. The manifest is a simple text file that adheres to a few conventions as required by the Application Cache API. A typical manifest file may resemble the following example:CACHE MANIFEST
# version 1
All files in the manifest are downloaded and stored in the application cache together. If a single file listed in the cache encounters a problem during transmission from the server to the client then an error is thrown and none of the files listed in the manifest are loaded into application cache. The all or nothing rule allows you to confidently rely on the existence of the application’s files in the application cache if the manifest downloads without error.
The following explanation dissects the example line-by-line to help you fully understand the mechanics of the manifest file.
Required and Implied Elements
The first line of any application manifest file must read CACHE MANIFEST. CACHE MANIFEST
This is a strict rule as you may not have whitespace, comments or any other information on the first line of the manifest. After leading with that term, then you have some flexibility as to how you craft the manifest file. The next section is the CACHE: section.CACHE:
The CACHE: section includes the list of all HTML, CSS, images and scripts files that make up the application. Files listed in the CACHE section may include any files regularly found as a part of a web application. You may reference any application files in the manifest. In this context, “application files” include static HTML pages, CSS files, images and scripts as well as server processed pages or files. The manifest only cares about the resulting file as served to the browser.
The heading of CACHE: is optional. Any file listed in the manifest file that does not appear under any other section heading is assumed to be a file to load into the application cache. This flexibility may prove helpful if you choose to generate your manifest file programmatically. However, for consistency and clarity, consider using the CACHE: heading in order to make your manifest easily understandable.
Maintaining Application Versions
The second line in the manifest listing is a comment. Any line that begins with the hash (#) symbol is a comment in the manifest file. # version 1
This comment, however, serves a specific purpose. In the Understanding Application Cache Event Lifecycle section later in this article, you’ll learn how the manifest file is used as the only point of reference to trigger changes in the application. In other words, if you save an update to the text in an HTML file and fail to make a change to the application manifest, then that change is never sent to the client. You must make a change in the manifest file so the update events fire for the application cache, which triggers a re-download of all the application’s files. Therefore, if you make a content change to an application file, you must have a mechanism for introducing change into the manifest file to prompt the client to re-download the contents of the manifest. A “version” comment works perfectly for this purpose.
The FALLBACK Section
Consider a page in the application that listed upcoming events as served from a database on the website. While this page is not accessible without an Internet connection, you want your users to see something other than an “unable to connect” error page (Figure 1) when they click on links to the Events page. The FALLBACK section maps server resources to alternatives available in the application cache.FALLBACK:
The FALLBACK section creates a mapping of alternative pages to serve to the user if a request to the original file fails or the computer is working offline. Associations between actual paths on the website and the fallback replacement are made by listing the full relative path to each location separated by a space.
While there are no wild cards allowed in fallback mapping definitions, URL patterns are respected in the FALLBACK section. For instance, if this website included thousands of headshots for every individual listed on the site, then you would not want to add each headshot to the manifest file. Adding all these files would bloat the payload of the application to include images that the user may never use. Instead, the FALLBACK section examines the /images/headshots/ path and knows that any path that includes /images/headshots/ is a part of the FALLBACK pattern and is served the mapped offline resource instead.
The NETWORK Section
The intent around the application manifest file is to define clear boundaries around the given application to ensure all the required resources are available on the client when there is no access to the Internet. While providing a cached option to the user is often possible, not all server resources are candidates for caching.
Search pages, dynamically constructed lists, user input forms and any other page that simply does not operate without the web server is not available for caching. The NETWORK section creates a whitelist of URLs that are excluded from control of the application cache. NETWORK:
This example lists the URL to the customer list page which is built from the database. Even though this URL is not listed in the CACHE section, without the entry in the NETWORK section, any requests for URL that are not cached are cancelled by the browser. Adding the path to the NETWORK officially excludes the given URL from the browser’s control to maintain the application cache and directly sends all requests to the server.
While wildcards are not allowed in the NETWORK section, the asterisk character (*) will whitelist any URL that is not explicitly listed in the CACHE section of the manifest file. Using the asterisk would change your NETWORK section to:NETWORK:
Mime Type and Encoding
In order to be processed correctly by the browser, the application manifest file must serve with the appropriate mime type and content encoding.
Manifest files must have the mime type of text/application-manifest. Further, the content encoding of the file must be set to UTF-8.
You may configure your web server to serve all files with the .appcache extension with the right mime type and content encoding. Alternatively, you may choose to set the mime type and encoding on the server for individual files. The example in this article configures each file individually.
Referencing the Manifest from the HTML Page
Once the manifest includes all the appropriate sections and is set to serve with the right mime type and content encoding, the manifest is ready to reference an HTML page.
To reference a manifest file in an HTML page, you use the new manifest attribute of the html element to point to the manifest file. If your manifest is a static file you may reference the file with the established .appcache file extension convention:<html manifest="manifest.appcache">
When the browser recognizes a value for the manifest attribute then it knows to treat the page as an HTML offline application and initiates the checking event against the manifest file.