Lesson 06-HTML5 Local Storage and Application Cache

LocalStorage

Web Storage includes two specific implementations: LocalStorage and sessionStorage

localStorage: key-value data stored in the user’s browser for a long time. Unless manually cleared, the data will remain. Even if the user closes the browser and reopens it, the data still exists. The capacity is generally around 5MB (depending on the browser implementation). Suitable for storing user preferences, settings, small amounts of non-sensitive data, etc.

// Check if the browser supports Web Storage
if ('localStorage' in window) {
    // Store data
    localStorage.setItem('key', 'value');

    // Get data
    const value = localStorage.getItem('key');

    // Delete data
    localStorage.removeItem('key');

    // Clear all data
    localStorage.clear();
}

SessionStorage

Web Storage includes two specific implementations: LocalStorage and sessionStorage

sessionStorage: Similar to localStorage, it also stores data in the form of key-value pairs, but its life cycle is bound to the browser session (session). When the browser window or tab is closed, the data in sessionStorage will be cleared. Suitable for temporary storage of data related to the current session, such as temporary form data, interface status, etc.

// Check if the browser supports Web Storage
if ('sessionStorage' in window) {
    // Store data
    sessionStorage.setItem('key', 'value');

    // Get data
    const value = sessionStorage.getItem('key');

    // Delete data
    sessionStorage.removeItem('key');

    // Clear all data
    sessionStorage.clear();
}

AppCache

Application Cache (AppCache) is an offline browsing technology provided by HTML5 that allows the website’s resources (HTML, CSS, JavaScript, images, etc.) to be cached to the user’s local system so that users can still access the application normally when there is no network connection or the network speed is slow. AppCache uses a manifest file called manifest to specify which resources should be cached.

Basic steps to use AppCache:

  • Create a manifest file (such as appcache.manifest) to list the resources to be cached:
CACHE MANIFEST
# Version 1.0
index.html
styles/main.css
scripts/app.js
images/logo.png
<!DOCTYPE html>
<html lang="en" manifest="appcache.manifest">
<head>
  <!-- ... -->
</head>
<body>
  <!-- ... -->
</body>
</html>
  • When the browser loads a page with the manifest attribute, it will automatically try to download and parse the manifest file and cache the specified resources as instructed.
  • When the network is unavailable or the user visits the application again, the browser will directly use the cached resources to render the page.

Although AppCache provides support for early offline applications, due to its design limitations and some known issues, such as complex update mechanism, strict HTTPS requirements, and no support for Service Workers, W3C has marked it as obsolete and recommended Service Workers as an alternative.

Service Workers

Service Workers is a script that runs independently of the main thread of the web page, which can intercept and process network requests, manage caches, implement offline functions, push notifications, background synchronization, etc. Compared with AppCache, Service Workers provides more refined control, more flexible caching strategies, and better update mechanisms.

Basic steps to use Service Workers:

  • Register Service Worker:
if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('/sw.js').then(registration => {
      console.log('Service Worker registered:', registration);
    }).catch(error => {
      console.error('Service Worker registration failed:', error);
    });
  });
}
  • Write Service Worker strategies in the sw.js file, such as caching resources, processing requests, implementing offline fallback logic, etc.:
// sw.js
self.addEventListener('install', event => {
  event.waitUntil(
    caches.open('my-app-cache').then(cache => {
      return cache.addAll([
        '/index.html',
        '/styles/main.css',
        '/scripts/app.js',
        '/images/logo.png'
      ]);
    })
  );
});

self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request).then(response => {
      return response || fetch(event.request);
    })
  );
});

In summary, HTML5 provides a variety of local storage and application cache technologies to meet different needs:

  • Web Storage (localStorage, sessionStorage): simple, lightweight key-value storage, suitable for small-scale data persistence.
  • IndexedDB: complex, powerful client-side database for storing large amounts of structured data.
  • Application Cache (AppCache): outdated offline browsing technology, replaced by Service Workers.
  • Service Workers: advanced technology supported by modern browsers for offline functions, network request interception and processing, resource cache management, etc.
Share your love