HTML5 Caching Explained: Mechanisms, Principles, and Mobile Optimization

This article introduces HTML5’s offline storage features, details six caching mechanisms—including browser cache, Web Storage, Web SQL, AppCache, IndexedDB, and the File System API—explains their principles, usage, and limitations, and demonstrates how to leverage them for improved mobile web performance in Android WebView.

21CTO
21CTO
21CTO
HTML5 Caching Explained: Mechanisms, Principles, and Mobile Optimization

1 H5 Cache Mechanism Introduction

HTML5 adds many new features, among which offline storage (also called caching) is crucial. It enables web applications to cache resources and be accessible without an Internet connection.

Advantages of HTML5 application cache:

Offline browsing – users can use the app when offline.

Speed – cached resources load faster.

Reduced server load – the browser only downloads updated resources.

According to the standard, there are six caching mechanisms in HTML5:

Browser cache mechanism

DOM Storage (Web Storage)

Web SQL Database

Application Cache (AppCache)

IndexedDB

File System API

We first analyze the principles, usage, and characteristics of each mechanism, then discuss how to improve Android mobile web performance by selecting appropriate caching strategies.

2 H5 Caching Mechanism Analysis

2.1 Browser Cache Mechanism

The browser cache uses HTTP headers such as Cache-Control (or Expires) and Last-Modified (or Etag) to control file caching. Cache-Control:max-age=600 means the file is valid locally for 600 seconds; during that period the browser serves the cached file without a network request. Last-Modified records the server’s latest update time. When the cache expires, the browser sends If-Modified-Since; the server replies 304 (not modified) or 200 (modified). Expires is an absolute timestamp (HTTP/1.0). When both Cache-Control and Expires appear, Cache-Control takes precedence. Etag is a unique string identifying a file. The browser sends If-None-Match with the Etag; a 304 response indicates no change.

Special cases:

Manual refresh (F5) forces Cache-Control:max-age=0, making the browser treat the cache as expired.

Force refresh (Ctrl+F5) adds Cache-Control:no-cache (or Pragma:no-cache), ignoring the local cache entirely.

Typical request/response flow captured in Chrome DevTools:

First request – 200

Within cache validity – 200 (from cache)

After expiration – 304 (Not Modified)

In Android WebView, cached files are stored in the app’s data directory.

Setting an appropriate cache duration is challenging: too short defeats caching, too long may serve stale resources. The “eliminate 304” approach avoids the extra validation request by embedding version strings or MD5 hashes in filenames and using Cache-Control:max-age=31536000 (one year).

2.2 DOM Storage (Web Storage)

Web Storage provides a larger, more secure, and convenient storage method than cookies. It stores string key/value pairs, offering about 5 MB per origin. It consists of sessionStorage (lifetime limited to a page session) and localStorage (persistent across sessions).

interface Storage { 
  readonly attribute unsigned long length; 
  [IndexGetter] DOMString key(in unsigned long index); 
  [NameGetter] DOMString getItem(in DOMString key); 
  [NameSetter] void setItem(in DOMString key, in DOMString data); 
  [NameDeleter] void removeItem(in DOMString key); 
  void clear();
};

Example of using sessionStorage to preserve form input after a page refresh:

<script type="text/javascript">
 window.onload = function(){
   if (window.sessionStorage) {
     var name = window.sessionStorage.getItem("name");
     if (name){
       document.getElementById("name").value = name;
     }
   }
 };
 function saveToStorage(){
   if (window.sessionStorage) {
     var name = document.getElementById("name").value;
     window.sessionStorage.setItem("name", name);
   }
 }
</script>
<form>
  <input type="text" id="name"/>
  <input type="button" value="Save" onclick="saveToStorage()"/>
</form>

LocalStorage works similarly but persists after the page is closed. Data is shared across all pages from the same origin.

<script>
  if (!localStorage.pageLoadCount) localStorage.pageLoadCount = 0;
  localStorage.pageLoadCount = parseInt(localStorage.pageLoadCount) + 1;
  document.getElementById('count').textContent = localStorage.pageLoadCount;
</script>
<p>You have viewed this page <span id="count"></span> time(s).</p>

In Android WebView, enable DOM Storage via:

WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setDomStorageEnabled(true);

2.3 Web SQL Database

Web SQL provides a relational database API based on SQLite. It is deprecated and no longer recommended; newer browsers favor IndexedDB.

<script>
 if(window.openDatabase){
   var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024);
   db.transaction(function (tx) {
     tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
     tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")');
     tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "logmsg")');
   });
   db.transaction(function (tx) {
     tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
       var len = results.rows.length, i, msg = "<p>Found rows: " + len + "</p>";
       for(i=0; i<len; i++){
         msg += "<p>" + results.rows.item(i).log + "</p>";
       }
       document.querySelector('#status').innerHTML = msg;
     }, null);
   });
 }
</script>
<div id="status">Status Message</div>

Typical quota is 5 MB per origin; browsers implement it using SQLite.

In Android WebView, enable Web SQL and set the database path:

WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setDatabaseEnabled(true);
String dbPath = getApplicationContext().getDir("db", Context.MODE_PRIVATE).getPath();
webSettings.setDatabasePath(dbPath);

2.4 Application Cache (AppCache)

AppCache allows offline web apps by listing resources in a manifest file. The HTML page includes manifest="demo_html.appcache". The manifest contains three sections: CACHE MANIFEST, NETWORK, and FALLBACK.

<!DOCTYPE html>
<html manifest="demo_html.appcache">
<body>
  <script src="demo_time.js"></script>
  <button onclick="getDateTime()">Get Date and Time</button>
  <img src="img_logo.gif">
</body>
</html>

Typical manifest file:

CACHE MANIFEST
# 2012-02-21 v1.0.0
/theme.css
/logo.gif
/main.js

NETWORK:
login.asp

FALLBACK:
/html/ /offline.html

AppCache is now deprecated and may be removed from future browsers.

Enable AppCache in Android WebView:

WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setAppCacheEnabled(true);
String cachePath = getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
webSettings.setAppCachePath(cachePath);
webSettings.setAppCacheMaxSize(5*1024*1024);

2.5 IndexedDB

IndexedDB is a NoSQL key‑value database offering large storage (default 250 MB per origin) and indexing capabilities.

Opening a database and creating an object store:

var request = indexedDB.open('mydb', 1);
request.onupgradeneeded = function(e){
  var db = e.target.result;
  var store = db.createObjectStore('people', {autoIncrement:true});
  store.createIndex('name','name',{unique:false});
  store.createIndex('email','email',{unique:true});
};

Querying by index:

function getPeopleByName(){
  var name = document.querySelector('#name1').value;
  var tx = db.transaction(['people'],'readonly');
  var store = tx.objectStore('people');
  var index = store.index('name');
  var request = index.get(name);
  request.onsuccess = function(e){
    var result = e.target.result;
    if(result){
      var html = "<h2>Name " + name + "</h2>";
      for(var field in result){
        html += field + "=" + result[field] + "<br/>";
      }
      document.querySelector('#status3').innerHTML = html;
    } else {
      document.querySelector('#status3').innerHTML = "<h2>No match!</h2>";
    }
  };
}

In Android 4.4+, IndexedDB works in WebView when JavaScript is enabled:

WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);

2.6 File System API

The File System API provides a sandboxed virtual file system for web apps, allowing creation, read, write, delete, and traversal of files and directories. It offers temporary and persistent storage; the latter requires user permission.

<script>
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
if (window.requestFileSystem) {
  window.requestFileSystem(window.TEMPORARY, 5*1024*1024, initFS, errorHandler);
} else { alert('Your browser does not support the FileSystem API'); }
function initFS(fs){
  fs.root.getFile('log.txt', {create:true}, function(fileEntry){
    writeFile(fileEntry);
    readFile(fileEntry);
  }, errorHandler);
}
function writeFile(fileEntry){
  fileEntry.createWriter(function(writer){
    var blob = new Blob(['Hello, World!'], {type:'text/plain'});
    writer.write(blob);
  }, errorHandler);
}
function readFile(fileEntry){
  fileEntry.file(function(file){
    var reader = new FileReader();
    reader.onloadend = function(){
      var ta = document.createElement('textarea');
      ta.value = this.result;
      document.body.appendChild(ta);
    };
    reader.readAsText(file);
  }, errorHandler);
}
function errorHandler(err){ console.log('Error: ' + err); }
</script>

File System API is currently supported only in Chrome (desktop and Android) and Opera.

3 Mobile Web Loading Performance (Caching) Optimization

After analyzing all HTML5 caching mechanisms, we return to the mobile scenario (Android, possibly iOS). Most Android apps embed a WebView to load H5 activity pages. While WebView offers rapid development, its loading speed can be slower and consume more traffic due to many HTTP requests for JS, CSS, fonts, and images.

By combining the caching mechanisms discussed, static resources (JS, CSS, fonts, images) should rely on the browser cache to improve speed and reduce traffic. Dynamic data can be cached with DOM Storage or IndexedDB to further cut server interactions.

Additional performance tips include optimizing image sizes and avoiding JS/CSS blocking.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

MobileHTML5IndexedDBWeb Storage
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.