阿里云主机折上折
  • 微信号
Current Site:Index > HTML5 Offline Application (Application Cache)

HTML5 Offline Application (Application Cache)

Author:Chuan Chen 阅读数:39577人阅读 分类: HTML

HTML5 Offline Applications (Application Cache) allow developers to create web applications that can run without an internet connection. By caching resource files, users can access the application offline, improving both user experience and performance.

Basic Concepts of Application Cache

Application Cache is a mechanism introduced in HTML5. It uses a manifest file to specify resources that should be stored offline. The browser downloads and caches these resources based on the manifest, enabling the application to function even without an internet connection. This technology is particularly suitable for web applications that require frequent access but have content that rarely changes.

How to Create a Manifest File

A manifest file is a text file, typically with the .appcache extension. It consists of three main sections:

  1. CACHE MANIFEST - Must appear on the first line of the file
  2. CACHE - Lists resources to be cached
  3. NETWORK - Lists resources that require online access

Example manifest.appcache file:

CACHE MANIFEST
# v1.0.0

CACHE:
index.html
styles/main.css
scripts/main.js
images/logo.png

NETWORK:
/api/

Linking the Manifest File in HTML

To use Application Cache in a webpage, add the manifest attribute to the <html> tag:

<!DOCTYPE html>
<html manifest="manifest.appcache">
<head>
    <title>Offline Application Example</title>
</head>
<body>
    <!-- Page content -->
</body>
</html>

How Application Cache Works

When a browser first loads a page with a manifest attribute, it follows these steps:

  1. Downloads and parses the manifest file
  2. Downloads and caches all resources listed in the CACHE section
  3. On subsequent visits, the browser checks if the manifest file has been updated
  4. If the manifest file has changed, all resources are re-downloaded

Cache Update Strategies

Cache updates follow these rules:

  • Changes to the manifest file content trigger updates
  • The browser only checks for changes in the manifest file itself, not the listed resources
  • A common technique is to add a version comment (e.g., # v1.0.1) to force updates

JavaScript example for checking updates:

if (window.applicationCache) {
    var appCache = window.applicationCache;
    
    appCache.addEventListener('updateready', function() {
        if (appCache.status === appCache.UPDATEREADY) {
            // Prompt the user to refresh for the new version
            if (confirm('A new version is available. Refresh now?')) {
                window.location.reload();
            }
        }
    }, false);
}

Handling Application Cache Events

The Application Cache API provides events to monitor cache status:

var appCache = window.applicationCache;

appCache.addEventListener('cached', handleCacheEvent, false);
appCache.addEventListener('checking', handleCacheEvent, false);
appCache.addEventListener('downloading', handleCacheEvent, false);
appCache.addEventListener('error', handleCacheError, false);
appCache.addEventListener('noupdate', handleCacheEvent, false);
appCache.addEventListener('obsolete', handleCacheEvent, false);
appCache.addEventListener('progress', handleCacheEvent, false);
appCache.addEventListener('updateready', handleCacheEvent, false);

function handleCacheEvent(e) {
    console.log('Cache event:', e.type);
}

function handleCacheError(e) {
    console.log('Cache error:', e);
}

Practical Considerations

  1. Cache Size Limits: Different browsers impose varying limits, typically around 5MB
  2. Mixed Content Issues: If a page is loaded via HTTPS, all cached resources must also be fetched via HTTPS
  3. Update Delays: Updated resources require a page refresh to take effect
  4. Fallback Mechanism: The FALLBACK section in the manifest can specify alternatives for unavailable resources

Example fallback configuration:

FALLBACK:
/ offline.html
images/ images/offline.png

Comparison with Service Workers

While Application Cache provides offline functionality, modern web applications increasingly prefer Service Workers because:

  • Service Workers offer finer-grained cache control
  • They support background sync and push notifications
  • They do not rely on manifest files, offering more flexible programming
  • They avoid some of the quirks of Application Cache

However, Application Cache remains relevant for projects with high compatibility requirements.

Debugging Application Cache

Chrome DevTools provides support for debugging Application Cache:

  1. Open DevTools (F12)
  2. Navigate to the Application panel
  3. Select Application Cache from the sidebar
  4. View the current page's cache status and resource list

Common Issues and Solutions

Issue 1: Updated resource files are not fetched by the browser

Solution:

  • Ensure the manifest file content is modified (e.g., version number)
  • Call applicationCache.update() to force an update check
  • Clear the browser cache

Issue 2: Some resources are not cached

Solution:

  • Verify resource URLs are correct
  • Ensure the server is configured with the correct MIME type for the manifest file (text/cache-manifest)
  • Confirm resources are accessible over the network

Performance Optimization Tips

  1. Cache rarely changing resources (e.g., framework libraries, UI components) separately
  2. Consider splitting large resources into smaller chunks
  3. Avoid caching frequently changing resources
  4. Use long-term caching for static resources like images

Example chunked caching strategy:

CACHE MANIFEST
# Framework resources
CACHE:
lib/angular.js
lib/bootstrap.css

NETWORK:
*

Browser Compatibility Status

Application Cache is supported by most modern browsers, but note:

  • Some mobile browsers may have incomplete implementations
  • Newer browser versions may gradually reduce support
  • Certain browsers enforce strict cache size limits

Role in Progressive Web Apps

Although Service Workers are replacing Application Cache, Application Cache played a significant role in the evolution of Progressive Web Apps (PWAs). Understanding its principles helps in mastering modern offline technologies.

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.