Home >Web Front-end >HTML Tutorial >How do I use the HTML5 Application Cache API (deprecated, use Service Workers instead)?
The HTML5 Application Cache API, though deprecated, was used to enable web applications to work offline by caching resources. Here's how you would have used it:
Manifest File: Create a manifest file with a .appcache
extension. This file lists resources that the browser should cache. The format of the manifest file is as follows:
<code>CACHE MANIFEST # v1 CACHE: /index.html /styles.css /script.js NETWORK: * FALLBACK: / /offline.html</code>
HTML Reference: Reference the manifest file in your HTML file by including the manifest
attribute in the tag:
<code class="html"></code>
CACHE
section.NETWORK
section are never cached, meaning they are always fetched from the network. The FALLBACK
section specifies fallback pages to serve when the user is offline.Important Note: Although these steps detail how the Application Cache API worked, it is deprecated and should not be used for new projects. Instead, developers should transition to Service Workers for managing offline functionality.
Transitioning from the Application Cache API to Service Workers involves several steps to ensure a smooth migration:
manifest
attribute from your HTML files and delete the .appcache
manifest files.Implement Service Worker: Register a Service Worker in your main JavaScript file:
<code class="javascript">if ('serviceWorker' in navigator) { window.addEventListener('load', function() { navigator.serviceWorker.register('/service-worker.js').then(function(registration) { console.log('ServiceWorker registration successful with scope: ', registration.scope); }, function(err) { console.log('ServiceWorker registration failed: ', err); }); }); }</code>
Write the Service Worker: Create a service-worker.js
file to handle the caching logic. Use the Cache API
for storing resources:
<code class="javascript">self.addEventListener('install', function(event) { event.waitUntil( caches.open('my-cache').then(function(cache) { return cache.addAll([ '/', '/index.html', '/styles.css', '/script.js' ]); }) ); }); self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request).then(function(response) { return response || fetch(event.request); }) ); });</code>
To ensure your web application remains offline-capable after migrating from the Application Cache API to Service Workers, consider the following:
Comprehensive Caching: Ensure that all critical resources necessary for your application to function offline are cached. This includes HTML, CSS, JavaScript, images, and any other assets. Use the Cache API
within your Service Worker to handle this:
<code class="javascript">self.addEventListener('install', function(event) { event.waitUntil( caches.open('my-cache').then(function(cache) { return cache.addAll([ '/', '/index.html', '/styles.css', '/script.js', '/offline.html' ]); }) ); });</code>
Handle Network Requests: Use the fetch
event to intercept and handle all network requests. If a resource is not found in the cache, you can attempt to fetch it from the network and then cache the response:
<code class="javascript">self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request).then(function(response) { return response || fetch(event.request).then(function(response) { return caches.open('my-cache').then(function(cache) { cache.put(event.request, response.clone()); return response; }); }); }) ); });</code>
Offline Fallback: Implement an offline fallback strategy. If a request fails, you can serve a fallback page from the cache:
<code class="javascript">self.addEventListener('fetch', function(event) { event.respondWith( fetch(event.request).catch(function() { return caches.match('/offline.html'); }) ); });</code>
Update Strategy: Ensure your Service Worker can update itself and the cache. Use versioning and the activate
event to manage updates:
<code class="javascript">self.addEventListener('activate', function(event) { var cacheWhitelist = ['my-cache-v2']; event.waitUntil( caches.keys().then(function(cacheNames) { return Promise.all( cacheNames.map(function(cacheName) { if (cacheWhitelist.indexOf(cacheName) === -1) { return caches.delete(cacheName); } }) ); }) ); });</code>
When migrating from the Application Cache API to Service Workers, it's important to understand the following key differences:
Flexibility and Control:
Scope and Capabilities:
Update Mechanism:
activate
event. You can explicitly define when and how caches are updated, providing more predictable and controlled updates.Performance and Efficiency:
Browser Support and Deprecation:
Understanding these differences will help you effectively migrate your application to Service Workers, ensuring a smooth transition and enhanced offline functionality.
The above is the detailed content of How do I use the HTML5 Application Cache API (deprecated, use Service Workers instead)?. For more information, please follow other related articles on the PHP Chinese website!