乐闻世界logo
搜索文章和话题

How can I cache external URLs using service worker?

1个答案

1

When using Service Worker to cache external URLs, first ensure you have permission to access these resources and adhere to the same-origin policy or the CORS headers provided by the resource. The following are the steps to cache external URLs using Service Worker:

Step 1: Register Service Worker

In your main JavaScript file, check if the browser supports Service Worker and register it if supported.

javascript
if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/service-worker.js') .then(function(registration) { console.log('Service Worker registered successfully: ', registration); }) .catch(function(error) { console.log('Service Worker registration failed: ', error); }); }

Step 2: Listen for the install Event

In your service-worker.js file, listen for the install event, which is the ideal time to precache resources.

javascript
const CACHE_NAME = 'external-resources-cache-v1'; const urlsToCache = [ 'https://example.com/external.css', // URL of external resources 'https://example.com/external.js' // URL of external resources ]; self.addEventListener('install', function(event) { event.waitUntil( caches.open(CACHE_NAME) .then(function(cache) { console.log('Cache opened'); return cache.addAll(urlsToCache); }) ); });

Note that the external resources you intend to cache must allow cross-origin access; otherwise, the browser's same-origin policy will prevent them from being cached.

Step 3: Intercept the fetch Event

Whenever the page attempts to fetch resources, the Service Worker can intercept the request and provide resources from the cache.

javascript
self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request) .then(function(response) { // Cache hit: return the cached resource if (response) { return response; } // Cache miss: initiate a request to fetch the resource and add it to the cache return fetch(event.request).then(function(response) { // Verify successful resource fetch if (!response || response.status !== 200 || response.type !== 'basic') { return response; } // Clone the response object as the request may need to be reused by the browser var responseToCache = response.clone(); caches.open(CACHE_NAME) .then(function(cache) { cache.put(event.request, responseToCache); }); return response; }); }) ); });

Note that if the response type is not 'basic', it may indicate a cross-origin request, and you must ensure the response includes CORS headers for Service Worker to handle it correctly.

Example:

Suppose we want to cache some library and font files from a CDN, as follows:

javascript
const urlsToCache = [ 'https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.min.js', 'https://fonts.googleapis.com/css?family=Roboto' ];

During the installation phase, the Service Worker will precache these files. During the request interception phase, when the application attempts to request these files, the Service Worker checks the cache and provides the cached response or fetches the resource from the network and adds it to the cache based on the above code.

This method can improve performance and reduce network dependency, but remember to manage cache updates, delete expired caches, and handle other lifecycle events within the Service Worker.

2024年6月29日 12:07 回复

你的答案