Sobes.tech
Middle

What is a cache in an HTML5 application?

sobes.tech AI

Answer from AI

The Application Cache in HTML5 is a mechanism that allows a web application to work offline by providing a set of resources (HTML pages, CSS, JavaScript, images) that the browser caches locally.

To use the application cache, a manifest file with the extension .appcache is required, which is linked to the HTML page via the manifest attribute of the <html> tag:

<html manifest="manifest.appcache">
...
</html>

The manifest file has the following structure:

CACHE MANIFEST
# Manifest version (optional, for cache update)
# v1.0

CACHE:
# Explicitly cached resources
/css/style.css
/js/script.js
/images/logo.png

FALLBACK:
# Backup resources in case of no connection
/offline.html /

NETWORK:
# Resources that should always be fetched from the network
*

Main sections of the manifest file:

  • CACHE:: Resources listed in this section will be cached after the first page load with the specified manifest.
  • FALLBACK:: Defines fallback resources. If a network request for a primary resource fails, the browser will load the specified fallback resource. Format: primary_resource fallback_resource.
  • NETWORK:: Resources listed here will never be cached and will always be fetched from the network. The * symbol means all resources not listed in other sections will always be fetched from the network.

The application cache is updated when the manifest file changes. The browser loads the updated manifest, compares it with the current one, and fetches new or changed resources. New files are available only after reloading the page.

Events related to the application cache:

  • checking: The browser checks for a new version of the manifest.
  • downloading: The browser downloads resources specified in the new manifest version.
  • progress: Progress of resource downloads.
  • updateready: A new cache version is ready to use. A page reload is required.
  • cached: Resources have been successfully cached for the first time.
  • noupdate: The manifest has not changed.
  • error: An error occurred during cache loading or updating.

The application cache API is accessible via window.applicationCache.

// Check cache status
console.log(window.applicationCache.status);

// Handle the updateready event
window.applicationCache.addEventListener('updateready', function() {
  if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
    // Apply the new cache version and reload the page
    window.applicationCache.swapCache();
    window.location.reload();
  }
}, false);

Although the Application Cache provided offline capabilities, its use is not recommended in new projects due to management complexity, update issues, and lack of flexibility. Modern approaches for offline access and other features of Progressive Web Apps (PWAs) use Service Workers.