Welcome!

Weblogic Authors: Yeshim Deniz, Elizabeth White, Michael Meiner, Michael Bushong, Avi Rosenthal

Related Topics: Machine Learning , Java IoT, Microservices Expo

Machine Learning : Article

Using HTML5 Application Cache to Create Offline Web Applications

Provides an easy way to prefetch some or all of your web app’s assets

Browser Support for HTML5 Offline Web Applications
Which browsers currently support offline web applications? The following table shows the browser support that's available for this feature at the time of this writing. As you can see, HTML5 Offline Web Applications are already supported in most browsers.

Browser

Details

Firefox

Supported in version 3.5 and later

Safari

Supported in version 4.0 and later

Chrome

Supported in version 4.0 and later

Opera

Supported in version 10.6 and later

Internet Explorer

Some day... Hopefully before we're all old and gray!

Note: Always go to http://caniuse.com to find the latest and greatest browser support matrixes for HTML5 and CSS3 features.

Due to the varying levels of support, it is a good idea to first test if HTML5 Offline Web Applications are supported, before you count on it. You can do this in two ways: with or without Modernizr as shown in the next example. I suggest using Modernizr (http://www.modernizr.com/) because it can handle certain tricky marginal cases. For example, in private browsing modes, such as Chrome's incognito mode, a call to window.applicationCache (more on this later) will return true, but the browser won't actually be able to write files to the cache.

if(window.applicationCache) {
// this browser supports offline web apps
}

//or using Modernizr
if (Modernizr.applicationcache){
// We have offline web app support
}

Creating a Manifest File
You can simply add some files to a cache as shown in the previous example, but you can also do more than that. Let's explore these options in more detail.

To ensure HTML5 interoperability, browsers must be very strict when it comes to reading files, so you must be very careful how you specify your files. If you don't pay attention to supplying the proper case, required colons, and formatting, you'll get undesired and sometimes puzzling results. Here are some general rules:

  • The first line of the file must always be CACHE MANIFEST.
  • Comments start with # and must appear on a line of their own.
  • File names must be listed exactly as they appear on disk (the file is case sensitive)

CACHE MANIFEST
# manifest version 1.0.1
# Files to cache

There are three name spaces; all of them can appear multiple times in the file:

  • CACHE:
  • NETWORK:
  • FALLBACK:

Let's take a look at each of these name spaces.

CACHE:
The files listed in this section will be cached in an application cache. If you only want to specify a list of files to be cached, you can simply add them under the CACHE MANIFEST directive without the CACHE: header, because this is the default behavior for files listed in the manifest file. However, if you want to flag files to be cached anywhere else in the file, you need to place them under an explicit CACHE: header (including the colon at the end, or you'll run into problems).

Here are the rules for the CACHE: section:

  • Only one file name per line.
  • A full file name is required (no wildcards allowed).
  • File names can contain path information or even an absolute URL.
  • Names can't include fragment identifiers (#, which is often used for bookmarks).

    Note: Files that reference the manifest file will automatically be cached in that application cache when they are visited, even if they are not referenced in the manifest file.

CACHE:
index.html
cache.html
html5.css
image1.jpg
favicon.ico

NETWORK:
This section is also called the "online whitelist." Files listed in this section will not be loaded from the application cache, but will be retrieved from the server if the browser is online. You can specify "*" (the default), which sets the online whitelist wildcard flag to "open", so that resources from other origins (an origin is the combination of a scheme, host, and port) will not be blocked. Here is an example NETWORK: section that specifies that the file network.html must always be retrieved from the server, bypassing the application cache:

# Use from network if available
NETWORK:
network.html

FALLBACK:
This section has a slightly different syntax than the other sections; it provides a way to specify a fallback resource that must be served if a specific resource cannot be found. An example of this is when the browser is offline and tries to load something that is not in the application cache, such as a page or JavaScript file listed in the NETWORK section. The following example shows how you can serve the page fallback.html when requests to server pages fail:

# Fallback content
FALLBACK:
/ fallback.html

To recap, here is our final manifest file, called offline.manifest:

CACHE MANIFEST
# manifest version 1.0.1

# Files to cache
index.html
cache.html
html5.css
image1.jpg
favicon.ico
# Use from network if available
NETWORK:
network.html
# Fallback content
FALLBACK:
/ fallback.html

Now that you've created your manifest file, you just need to reference it by adding the manifest attribute to the html elements of the HTML pages that you want to cache (cache.html and index.html). You do this as follows:

<!DOCTYPE html>
<html manifest="offline.manifest">

Serving the Manifest File
Just like you want a nice pasta dish served up al dente, you want your manifest files served up with the text/cache-manifest MIME type. You will find, however, that very few web servers will do this correctly out-of-the-box. Instead, you'll find that files will be served in either text or binary mode-and neither one will work. You can test this by using navigation to the file in a browser and looking at the properties for the file. Most web servers provide a way to configure the mime types for specific file extensions, so once you just update the mime type configuration file on the server, you're all set.

On Apache, you can change this globally in the mime.types file:

# Apache mimetype configuration
# APACHE_HOME/conf/mime.types
text/cache-manifest manifest

Alternatively, you can update the .htaccess file for an individual web application:

# Apache mimetype configuration
AddType text/cache-manifest .manifest

Oh, and while you're changing your Apache configuration, take this good advice from Bruce Lawson and Remy Sharp in their excellent book Introducing HTML5. Set the cache control headers for the manifest file to prevent the manifest file from being cached. If you don't, you'll wish you did, because as you'll soon see, the manifest file must be updated in order to trigger any web app updates that you download. In other words, the manifest file is not a file you want to cache! You can do this in your .htaccess file as well:

# Cache settings for the manifest file
<IfModule mod_expires.c>
Header set cache-control: public
ExpiresActive on
# Prevent receiving a cached manifest
ExpiresByType text/cache-manifest "access plus 0 seconds"
</IfModule>

For Python's SimpleHTTPServer-a great server to do some quick testing-you can update the mimetypes section in the file mimetypes.py located in the PYTHON_HOME/Lib directory as follows:

# Python SimpleHTTPServer mimetype Configuration
'.manifest'    : 'text/cache-manifest',

Note: If you do not have a mimetypes.py file (this happens a lot on default Mac installations, in which you'll probably have a compiled mimetypes.pyc file instead), you can use the sample mimetypes.py file located in the mac-config-file directory in the starter file ZIP file. Make sure that the permissions on this file are changed to read/write. When you start Python with the new file, Python compiles it and generates a new mimetypes.pyc.

Application Cache Sequences
Let's see what's happening behind the scenes when you access a web app that uses an application cache. When you first access your web app, the following sequence of events takes place:

  • You access the index page (which has the manifest attribute set).
  • The index page is loaded and the page's resources (any relevant images, CSS, JavaScript, and so on) are loaded from the server and at the same time stored in the regular browser cache.
  • While parsing the page, the manifest file is encountered and parsed, and all files flagged for caching are downloaded in the background and stored in a new application cache. (Note that the index page and its resources will actually be downloaded again in this case).


The initial page load

  • You go offline. Regular caching is also in effect, so watch for false positives here. Files you visited online may be available in offline mode, but that is no indication that they've been pulled from an application cache (they may just be cached instead).


Going Offline in Firefox

Note: In Opera and Firefox you can go offline by selecting File > Work Offline, but a similar option does not exist (unfortunately) in Chrome or Safari. As a workaround, I've found that specifying a made-up proxy server in the LAN settings can give you the same effect after the browser times out looking for the non-existent proxy server.

  • You access a CACHE resource (one you have not visited while you're online) and check that this file and its resources load from the application cache.

The cache page loads from the application cache

  • You access a NETWORK resource and check that the FALLBACK content is served instead, because NETWORK files will be available if you go back online).

Fallback content is served when you try to access a network resource in offline mode

You might be surprised by what happens the next time you visit the app, when the following sequence of events takes place:

  • You go back to online mode.
  • You change a file (for example, cache.html) page on the server.
  • You reload the cache.html page in the browser.
  • The (old) page loads from the application cache. That's right - even though you're back online, the changes do not appear, because once a file is cached in the application cache, it will always be served up from there first when a request is made for that file.
  • The browser now checks to see if the referenced manifest file has been updated and does nothing, since it has not been modified.

Important: This is an important detail about application caching and application cache busting: New files will be downloaded only when a change in the manifest file is detected.

  • You update the manifest file.

Best Practice: if you only made a content change to an existing file (cache.html), then no files were added or removed and you obviously don't really have to make changes to the manifest file. In this case you can make a trivial change such as adding a comment. As a best practice, use a version number comment each time you make any change to force the download of your app's files.

  • You reload the cache page in the browser once more.
  • The (old) page loads again from the application cache, and since this is always the first action from the browser, the changes still don't appear!
  • The browser checks to see if the referenced manifest has been updated, and since it has changed this time, it requests all the files flagged to be cached from the server (It may receive 304 (Not Modified) codes for files that have not changed, but it checks each file referenced in the file.

See Also: Check out the following, related proposal to enhance Application Cache for better performance by Google's Seth Ladd: http://blog.sethladd.com/2010/10/proposal-to-enhance-html5-app-cache.html

  • The new files are now in the latest version application cache, so you now just reload the page once more to (finally) see the latest changes.

Try this out in different browsers. The current implementations are not completely interoperable yet, but it's a good start. One browser that has great support for Application Cache is Google Chrome. In the recent versions of the developer channel for this browser, there is complete support for application cache and application cache events in the storage tab as shown in the following image:

Google Chrome Developer Tools Application Cache Storage View

More Stories By Peter Lubbers

Peter Lubbers is the Director of Documentation and Training at Kaazing where he oversees all aspects of documentation and training. He is the co-author of the Apress book Pro HTML5 Programming and teaches HTML5 training courses. An HTML5 and WebSocket enthusiast, Peter frequently speaks at international events.

Prior to joining Kaazing, Peter worked as an information architect at Oracle, where he wrote many books. He also develops documentation automation solutions and two of his inventions are patented.

A native of the Netherlands, Peter served as a Special Forces commando in the Royal Dutch Green Berets. In his spare time (ha!) Peter likes to run ultra-marathons. He is the 2007 and 2009 ultrarunner.net series champion and three-time winner of the Tahoe Super Triple marathon. Peter lives on the edge of the Tahoe National Forest and loves to run in the Sierra Nevada foothills and around Lake Tahoe (preferably in one go!).

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


IoT & Smart Cities Stories
Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...
Whenever a new technology hits the high points of hype, everyone starts talking about it like it will solve all their business problems. Blockchain is one of those technologies. According to Gartner's latest report on the hype cycle of emerging technologies, blockchain has just passed the peak of their hype cycle curve. If you read the news articles about it, one would think it has taken over the technology world. No disruptive technology is without its challenges and potential impediments t...
If a machine can invent, does this mean the end of the patent system as we know it? The patent system, both in the US and Europe, allows companies to protect their inventions and helps foster innovation. However, Artificial Intelligence (AI) could be set to disrupt the patent system as we know it. This talk will examine how AI may change the patent landscape in the years to come. Furthermore, ways in which companies can best protect their AI related inventions will be examined from both a US and...
Bill Schmarzo, Tech Chair of "Big Data | Analytics" of upcoming CloudEXPO | DXWorldEXPO New York (November 12-13, 2018, New York City) today announced the outline and schedule of the track. "The track has been designed in experience/degree order," said Schmarzo. "So, that folks who attend the entire track can leave the conference with some of the skills necessary to get their work done when they get back to their offices. It actually ties back to some work that I'm doing at the University of San...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...