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
DX World EXPO, LLC, a Lighthouse Point, Florida-based startup trade show producer and the creator of "DXWorldEXPO® - Digital Transformation Conference & Expo" has announced its executive management team. The team is headed by Levent Selamoglu, who has been named CEO. "Now is the time for a truly global DX event, to bring together the leading minds from the technology world in a conversation about Digital Transformation," he said in making the announcement.
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Conference Guru has been named “Media Sponsor” of the 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. A valuable conference experience generates new contacts, sales leads, potential strategic partners and potential investors; helps gather competitive intelligence and even provides inspiration for new products and services. Conference Guru works with conference organizers to pass great deals to gre...
The Internet of Things will challenge the status quo of how IT and development organizations operate. Or will it? Certainly the fog layer of IoT requires special insights about data ontology, security and transactional integrity. But the developmental challenges are the same: People, Process and Platform. In his session at @ThingsExpo, Craig Sproule, CEO of Metavine, demonstrated how to move beyond today's coding paradigm and shared the must-have mindsets for removing complexity from the develop...
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...
"Evatronix provides design services to companies that need to integrate the IoT technology in their products but they don't necessarily have the expertise, knowledge and design team to do so," explained Adam Morawiec, VP of Business Development at Evatronix, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
Large industrial manufacturing organizations are adopting the agile principles of cloud software companies. The industrial manufacturing development process has not scaled over time. Now that design CAD teams are geographically distributed, centralizing their work is key. With large multi-gigabyte projects, outdated tools have stifled industrial team agility, time-to-market milestones, and impacted P&L stakeholders.
"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.
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
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 ...
"Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, 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.
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
"There's plenty of bandwidth out there but it's never in the right place. So what Cedexis does is uses data to work out the best pathways to get data from the origin to the person who wants to get it," explained Simon Jones, Evangelist and Head of Marketing at Cedexis, 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.
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
SYS-CON Events announced today that Telecom Reseller has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.