问题
Following is the code for the SW, all working fine. I was caching all the dynamic pages previously, but this was creating me some issues. Like page DOM changes after users interaction are not reflected next time page view. Always it shows original DOM.
SO I have needed the only image caching dynamically. I have commented original code which was caching all content.
self.addEventListener('activate', function(event) {
console.log('[Service Worker] Activating Service Worker ....', event);
/*event.waitUntil(
caches.keys()
.then(function(keyList) {
return Promise.all(keyList.map(function(key) {
if (key !== CACHE_STATIC_NAME && key !== CACHE_DYNAMIC_NAME) {
console.log('[Service Worker] Removing old cache.', key);
return caches.delete(key);
}
}));
})
);*/
return self.clients.claim();
});
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
if (response) {
return response;
} else {
/*return fetch(event.request)
.then(function(res) {
return caches.open(CACHE_DYNAMIC_NAME)
.then(function(cache) {
/!*if ( event.request.url.indexOf( 'maps.google' ) !== -1 ) {
return false;
}*!/
if (!/^https?:$/i.test(new URL(event.request.url).protocol)) {
return;
}
cache.put(event.request.url, res.clone());
return res;
})
})
.catch(function(err) {
console.log('show offline page as cashe and network not available')
return caches.open(CACHE_STATIC_NAME)
.then(function (cache) {
return cache.match(OFFLINE_URL);
});
});*/
return fetch(event.request);
}
})
);
});
回答1:
I'd recommend following the approach outlined in this "Service Worker Caching Strategies Based on Request Types" article, and use request.destination
inside of your fetch
handler to figure out which requests are going to be used for images.
self.addEventListener('fetch', (event) => {
if (event.request.destination === 'image') {
event.respondWith(/* your caching logic here */);
}
// If you don't call event.respondWith() for some requests,
// the normal loading behavior will be used by default.
};
It's possible that a request for an image might be loaded via something like XMLHttpRequest, in which case the request.destination
value likely won't be set properly. If that's the case, I'd recommend just checking the portion of the URL you feel is most likely to be unique using string comparisons.
self.addEventListener('fetch', (event) => {
const url = new URL(event.request.url);
if (url.origin.includes('maps.google')) {
event.respondWith(/* your caching logic here */);
}
// If you don't call event.respondWith() for some requests,
// the normal loading behavior will be used by default.
};
来源:https://stackoverflow.com/questions/60814757/caching-only-images-inside-of-a-service-worker