1. HTML5 Cache Mechanism & Local Storage
Ver : 1.0
Name: Sendhil Kumar K
Title: HTML5 Cache Mechanism &
Local Storage
Email: Sen_5k@msn.com
2. • HTML5 introduces Application Cache, which is also
known as appCache in short.
• appCache enables a Website or Web Application to
be cached and works even when Internet
connectivity is unavailable.
• appCache coupled with Session and Local Storage,
Indexed DB and Web SQL are extensively used in
mobile apps.
2
What is HTML5 Application Cache?
3. • Application Cache provides reliable caching mechanism in addition to
browser ‘s default cache. In order to enable the Application Cache you
need to include the manifest attribute on the HTML tag.
• Application Cache allows a developer to specify which files the browser
should cache and make available to offline. Your website/web
application will load and work correctly, even if the user presses the
refresh button while they're offline.
• Application Cache can also be used online to decrease the load times of
the document, by fetching the required resources like CSS, JS and
IMAGES at once and makes them available to the browser locally for
entire application.
3
Introduction to Application Cache
4. • The cache manifest file is a simple text file that lists the resources
browser should cache for offline access. Manifest file needs to be
modified to refresh cached files.
• Manifest attribute needs to be added to the <html> tag to enable
Application Cache. The recommended file extension for manifest file is
‘.appcache’. Manifest file can point to absolute URL or relative path.
• A manifest file needs to be served with the correct media type, which is
"text/cache-manifest". Must be configured on the web server.
4
HTML5 Caching Mechanism - Cache Manifest Basics
<!DOCTYPE HTML>
<html manifest="demo.appcache">
...
</html>
5. • Manifest file should start with ‘CACHE MANIFEST’ line and this line is
mandatory, followed by the list of files to be cached.
• If Manifest file or a Resource fails to download, the entire cache update
process fails and starts using old cache file.
• Simple structure of Manifest file is as below:
5
HTML5 Caching Mechanism - Cache Manifest Basics
CACHE MANIFEST
# Comented Line
# Manifest Version 1.0 Dated – 29-12-2014
index.html
stylesheet.css
images/logo.png
scripts/main.js
http://www.yourdomain.com/images/myPhoto.jpg
6. • Manifest file can have three distinct sections: CACHE, NETWORK and
FALLBACK.
• Files listed under CACHE: or immediately after CACHE MANIFEST Line
are explicitly cached after they’re downloaded for the first time.
• Files listed under NETWORK: section are white-listed file/resource that
requires a connection to the server. Wild card characters can be used for
the file or resource representation.
• Files listed under FALLBACK: section specifies fallback pages to be
used if a resource is inaccessible. Each entry in this section lists two
URIs—the first is the resource, the second is the fallback. Both URIs
must be relative and from the same origin as the manifest file. Wild card
can be used.
• All 3 sections can be listed in any order in a cache manifest file, and
each section can appear more than once in a single manifest file.
HTML5 Caching Mechanism - Cache Manifest Basics
7. • Sample Manifest file with all the three distinct sections: CACHE,
NETWORK and FALLBACK sections looks like below:
7
HTML5 Caching Mechanism - Cache Manifest Basics
CACHE MANIFEST
# Comented Line
# Manifest Version 2 Dated – 1-1-2015
CACHE:
/favicon.ico
index.html
stylesheet.css
images/logo.png
scripts/main.js
#Resources that require the user to be online.
NETWORK:
*
FALLBACK:
# static.html will be served if main.php is inaccessible
/main.php /static.html
# offline.jpg will be served in place of all images in images/large/
images/large/ images/offline.jpg
8. • Sample 3 page demo using Manifest file.
• Manifest file used for Demo:
8
HTML5 Caching Mechanism - Demo using Manifest File
9. Application Cache can be updated using following methods:
•The user clears the cache manually and refresh’s the page.
•Updating the manifest file with latest version of new files to be cached.
•The cache can also be updated using JavaScript Application Cache API.
Note: Updating a file listed in the manifest doesn't mean the browser will re-
cache that resource. The manifest file itself must be altered.
9
HTML5 Caching Mechanism - Updating Cache using Manifest File
10. • window.applicationCache object is your programmatic access to the
browser's app cache.
• Detecting browser for applicationCache API Support:
• window.applicationCache object allows you to:
– know the cache states
– do event management to detect when the Application Cache
changes status
– update the cache
– change the current cache
10
HTML5 Caching Mechanism - JavaScript API for AppCache
if(window.applicationCache)
//Supports application Cache
else
//Does’nt Support applicationCache
11. • Each application cache has a state, which indicates the current condition of
the cache. Caches that share the same manifest URI share the same cache
state, which can be one of the following:
– UNCACHED - A special value that indicates that an application cache object is
not fully initialized.
– IDLE - The application cache is not currently in the process of being updated.
– CHECKING - The manifest is being fetched and checked for updates.
– DOWNLOADING - Resources are being downloaded to be added to the cache,
due to a changed resource manifest.
– UPDATEREADY - There is a new version of the application cache available.
There is a corresponding updateready event, which is fired instead of the cached
event when a new update has been downloaded but not yet activated using the
swapCache() method.
– OBSOLETE - The application cache group is now obsolete.
11
HTML5 Caching Mechanism - JavaScript API for AppCache
12. • Cache update canbe explicitly invoked programatically as below:
12
HTML5 Caching Mechanism - JavaScript API for AppCache
<script type="text/javascript">
function OnLoad() {
window.applicationCache.addEventListner('updateready', function (e) {
if(window.applicationCache.status == window.applicationCache.UPDATEREADY) {
window.applicationCache.swapCache();
}
});
}
function UpdateCache() {
window.applicationCache.update();
}
</script>
• applicationCache.update() will check if a cache update is required or not and
return the status to the callback function. Calling applicationCache.swapCache()
on UPDATEREADY status will pull the modified cache resources from the server
and update the local cache content.
13. • Sample 3 page demo using JavaScript appCache API.
• JavaScript Event targeting code used for Demo:
13
HTML5 Caching Mechanism - Demo using JavaScript appCache API
// add listeners on page load and unload
window.addEventListener("load", loadDemo, true);
var counter = 1;
appCacheLog = function() {
var p = document.createElement("p");
var message = Array.prototype.join.call(arguments, " ");
p.innerHTML = message;
document.getElementById("info").appendChild(p);
}
// log each of the events fired by window.applicationCache
window.applicationCache.onchecking = function(e) {
appCacheLog("Checking for updates");
}
window.applicationCache.onnoupdate = function(e) {
appCacheLog("No updates found");
}
window.applicationCache.onupdateready = function(e) {
appCacheLog("Update complete");
}
14. • HTML 5 introduced Local Storage for explicitly storing data locally in Key
value pair.
• Local storage is more secure and large amounts of data can be stored
locally with out affecting website performance. Local storage is stored
and retrieved on per domain basis.
• Local and Session storage can be used in addition to storing data in
cookies. Information stored in Local storage is never transferred to the
server.
• Local storage is supported in Internet Explorer 8 and above, Firefox 31
and above, Opera 26 and above, Chrome 31 and above, and Safari 5.1
and above.
14
HTML5 Caching Mechanism - Local Storage
15. • In HTML 5, Local storage provides two objects for storing data on the client:
– window.localStorage - stores data with no expiration date in the form Key/Value pair
– window.sessionStorage - stores data for the session till that tab/window is open
• Browser support detection for Local Storage:
15
HTML5 Caching Mechanism - Local Storage JavaScript Object
if(typeof(Storage)!=="undefined")
{
// Browser supports localStorage/sessionStorage.
} else {
// Browser doesn't support localStorage/sessionStorage.
}
16. • localStorage object stores the data with no expiration date. The data will
not be deleted when the browser is closed, and will be available the next
day, week, or year.
16
HTML5 Caching Mechanism - localStorage Object
// Store
localStorage.setItem(‘company’, ‘Cignex Datamatics Pvt Ltd.’);
// Retrieve
localStorage.getItem(‘company’);
//Delete
localStorage.removeItem(‘company’);
//Clearing localStorage
localStorage.clear();
17. • sessionStorage object is equal to the localStorage object, except that it
stores the data for only one session. The data is deleted when the user
closes the browser window.
17
HTML5 Caching Mechanism - sessionStorage Object
// Store
sessionStorage.setItem(‘company’, ‘Cignex Datamatics Pvt Ltd.’);
// Retrieve
sessionStorage.getItem(‘company’);
//Delete
sessionStorage.removeItem(‘company’);
//Clearing sessionStorage
sessionStorage.clear();
18. Advantages
• Offline browsing - users can interact
with your full application even when
they're offline.
• Speed - resources come straight
from disk, no trip to the network.
• Reduce server load - server will
send the files that have changed
since the last visit of the user.
• Resilience - if your site goes down
for "maintenance", your users will
get the offline experience.
• Synchronize - synchronize data
once you’re back online.
Dis-advantages
• Need to update manifest file
frequently on content or resources
update.
• Application Cache gets deleted
when browser’s cache is cleared.
• Varied Browser support limitations.
18
Advantages and Disadvantages of Application Cache
19. • Browsers may have different size limits for cached data (some browsers have
a 5MB limit per site).
• Internet Explorer 10 and above, Firefox 3.5 and above, Chrome 5.0 and
above, Safari 4.0 and above and Opera10.6 and above support Application
cache.
• All Major Mobile Browsers support Application Cache.
• List of major browsers that support Application Cache, Session and Local
Storage, Indexed DB and Web SQL can be accessed from here.
• Application Cache Browser Implementation guides for Firefox , Safari and IE.
19
Browser Support and Limitations – Application Cache
20. 20
Browser Support and Limitations – Local Storage
Courtesy: http://caniuse.com/#search=Local%20Storage
21. 21
Browser Support and Limitations – Application
Cache
Courtesy: http://caniuse.com/#search=application%20cache
23. • Offline Web Application
• The cache manifest syntax
• Security concerns with offline applications caches
• Application cache API
• Browser state
23
W3C Standard Specification Links for Application Cache