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
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, discussed how they built...
In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...
The 22nd International Cloud Expo | 1st DXWorld Expo has announced that its Call for Papers is open. Cloud Expo | DXWorld Expo, to be held June 5-7, 2018, at the Javits Center in New York, NY, brings together Cloud Computing, Digital Transformation, Big Data, Internet of Things, DevOps, Machine Learning and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding busin...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
DevOps at Cloud Expo – being held June 5-7, 2018, at the Javits Center in New York, NY – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real results. Among the proven benefits,...
@DevOpsSummit at Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, is co-located with 22nd Cloud Expo | 1st DXWorld Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
SYS-CON Events announced today that T-Mobile exhibited at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on qua...
SYS-CON Events announced today that Cedexis will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Cedexis is the leader in data-driven enterprise global traffic management. Whether optimizing traffic through datacenters, clouds, CDNs, or any combination, Cedexis solutions drive quality and cost-effectiveness. For more information, please visit https://www.cedexis.com.
SYS-CON Events announced today that Google Cloud has been named “Keynote Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Companies come to Google Cloud to transform their businesses. Google Cloud’s comprehensive portfolio – from infrastructure to apps to devices – helps enterprises innovate faster, scale smarter, stay secure, and do more with data than ever before.
SYS-CON Events announced today that Vivint to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. As a leading smart home technology provider, Vivint offers home security, energy management, home automation, local cloud storage, and high-speed Internet solutions to more than one million customers throughout the United States and Canada. The end result is a smart home solution that sav...
SYS-CON Events announced today that Opsani will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Opsani is the leading provider of deployment automation systems for running and scaling traditional enterprise applications on container infrastructure.
SYS-CON Events announced today that Nirmata will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Nirmata provides a comprehensive platform, for deploying, operating, and optimizing containerized applications across clouds, powered by Kubernetes. Nirmata empowers enterprise DevOps teams by fully automating the complex operations and management of application containers and its underlying ...
SYS-CON Events announced today that Opsani to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. Opsani is creating the next generation of automated continuous deployment tools designed specifically for containers. How is continuous deployment different from continuous integration and continuous delivery? CI/CD tools provide build and test. Continuous Deployment is the means by which...