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.


@ThingsExpo Stories
JETRO showcased Japan Digital Transformation Pavilion at SYS-CON's 21st International Cloud Expo® at the Santa Clara Convention Center in Santa Clara, CA. The Japan External Trade Organization (JETRO) is a non-profit organization that provides business support services to companies expanding to Japan. With the support of JETRO's dedicated staff, clients can incorporate their business; receive visa, immigration, and HR support; find dedicated office space; identify local government subsidies; get...
DXWorldEXPO LLC announced today that All in Mobile, a mobile app development company from Poland, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. All In Mobile is a mobile app development company from Poland. Since 2014, they maintain passion for developing mobile applications for enterprises and startups worldwide.
@DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22nd international CloudEXPO | first international DXWorldEXPO and will feature technical sessions from a rock star conference faculty and the leading industry players in the world.
"Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
As data explodes in quantity, importance and from new sources, the need for managing and protecting data residing across physical, virtual, and cloud environments grow with it. Managing data includes protecting it, indexing and classifying it for true, long-term management, compliance and E-Discovery. Commvault can ensure this with a single pane of glass solution – whether in a private cloud, a Service Provider delivered public cloud or a hybrid cloud environment – across the heterogeneous enter...
DXWorldEXPO LLC announced today that ICC-USA, a computer systems integrator and server manufacturing company focused on developing products and product appliances, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City. ICC is a computer systems integrator and server manufacturing company focused on developing products and product appliances to meet a wide range of ...
More and more brands have jumped on the IoT bandwagon. We have an excess of wearables – activity trackers, smartwatches, smart glasses and sneakers, and more that track seemingly endless datapoints. However, most consumers have no idea what “IoT” means. Creating more wearables that track data shouldn't be the aim of brands; delivering meaningful, tangible relevance to their users should be. We're in a period in which the IoT pendulum is still swinging. Initially, it swung toward "smart for smart...
Headquartered in Plainsboro, NJ, Synametrics Technologies has provided IT professionals and computer systems developers since 1997. Based on the success of their initial product offerings (WinSQL and DeltaCopy), the company continues to create and hone innovative products that help its customers get more from their computer applications, databases and infrastructure. To date, over one million users around the world have chosen Synametrics solutions to help power their accelerated business or per...
In an era of historic innovation fueled by unprecedented access to data and technology, the low cost and risk of entering new markets has leveled the playing field for business. Today, any ambitious innovator can easily introduce a new application or product that can reinvent business models and transform the client experience. In their Day 2 Keynote at 19th Cloud Expo, Mercer Rowe, IBM Vice President of Strategic Alliances, and Raejeanne Skillern, Intel Vice President of Data Center Group and ...
Founded in 2000, Chetu Inc. is a global provider of customized software development solutions and IT staff augmentation services for software technology providers. By providing clients with unparalleled niche technology expertise and industry experience, Chetu has become the premiere long-term, back-end software development partner for start-ups, SMBs, and Fortune 500 companies. Chetu is headquartered in Plantation, Florida, with thirteen offices throughout the U.S. and abroad.
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
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...
"We are a well-established player in the application life cycle management market and we also have a very strong version control product," stated Flint Brenton, CEO of CollabNet,, in this SYS-CON.tv interview at 18th Cloud Expo at the Javits Center in New York City, NY.
It is of utmost importance for the future success of WebRTC to ensure that interoperability is operational between web browsers and any WebRTC-compliant client. To be guaranteed as operational and effective, interoperability must be tested extensively by establishing WebRTC data and media connections between different web browsers running on different devices and operating systems. In his session at WebRTC Summit at @ThingsExpo, Dr. Alex Gouaillard, CEO and Founder of CoSMo Software, presented ...
Most people haven’t heard the word, “gamification,” even though they probably, and perhaps unwittingly, participate in it every day. Gamification is “the process of adding games or game-like elements to something (as a task) so as to encourage participation.” Further, gamification is about bringing game mechanics – rules, constructs, processes, and methods – into the real world in an effort to engage people. In his session at @ThingsExpo, Robert Endo, owner and engagement manager of Intrepid D...
Recently, WebRTC has a lot of eyes from market. The use cases of WebRTC are expanding - video chat, online education, online health care etc. Not only for human-to-human communication, but also IoT use cases such as machine to human use cases can be seen recently. One of the typical use-case is remote camera monitoring. With WebRTC, people can have interoperability and flexibility for deploying monitoring service. However, the benefit of WebRTC for IoT is not only its convenience and interopera...
Michael Maximilien, better known as max or Dr. Max, is a computer scientist with IBM. At IBM Research Triangle Park, he was a principal engineer for the worldwide industry point-of-sale standard: JavaPOS. At IBM Research, some highlights include pioneering research on semantic Web services, mashups, and cloud computing, and platform-as-a-service. He joined the IBM Cloud Labs in 2014 and works closely with Pivotal Inc., to help make the Cloud Found the best PaaS.
Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution. In his session at @ThingsExpo, Akvelon expert and IoT industry leader Sergey Grebnov provided an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.