swcache/cachersw.js

99 lines
4.1 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
*
A service worker is simply a file (it has no access to DOM):
1. Here we add an install event listener to the service worker (using self), and then chain a ExtendableEvent.waitUntil() method onto the event —
this ensures that the service worker will not install until the code inside waitUntil() has successfully occurred.
2. Inside waitUntil() we use the caches.open() method to create a new cache called v1, which will be version 1 of our site resources cache.
This returns a promise for a created cache; once resolved, we then call a function that calls addAll() on the created cache,
which for its parameter takes an array of origin-relative URLs to all the resources you want to cache.
3. If the promise is rejected, the install fails, and the worker wont do anything.
This is ok, as you can fix your code and then try again the next time registration occurs.
4.After a successful installation, the service worker activates.
This doesnt have much of a distinct use the first time your service worker is installed/activated,
but it means more when the service worker is updated...
*
*
* */
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open('v1').then((cache) => {
/*
The addAll() method of the Cache interface takes an array of URLs, retrieves them, and adds the resulting response objects to the given cache.
The request objects created during retrieval become keys to the stored response operations.
*/
return cache.addAll([
//'/imgs/180295.jpg',
//'/imgs/180343.jpg',
//'/imgs/180401.jpg',
//'/imgs/1920x1200-Linux Widescreen705729403.jpg',
//'/imgs/2551508.jpg'
]);
}));
});
/*
*
*
NOTE:
The clone is put in the cache, and the original response is returned to the browser to be given to the page that called it.
Cloning the response is necessary because request and response streams can only be read once.
In order to return the response to the browser and put it in the cache we have to clone it.
So the original gets returned to the browser and the clone gets sent to the cache. They are each read once.
The only trouble we have now is that if the request doesnt match anything in the cache, and the network is not available, our request will still fail.
If you want provide a default fallback so that whatever happens, use the callback
*
*
*/
self.fetch_and_cache = function (evreq) {
return fetch(evreq).then((response) => {
return caches.open('v1').then((cache) => {
console.log('fetch and cache ' + evreq);
cache.put(evreq, response.clone());
return response
}).catch(() => {
console.log('___ here a callback ___');
});
});
}
/**
*
*
A fetch event fires every time any resource controlled by a service worker is fetched, which includes the documents inside the specified scope,
and any resources referenced in those documents (for example if index.html makes a cross origin request to embed an image, that still goes through its service worker.)
You can attach a fetch event listener to the service worker, then call the respondWith() method on the event to hijack our HTTP responses and update them with your own magic.
*
*
*/
self.addEventListener('fetch', (event) => {
/**
*
caches.match(event.request) allows us to match each resource requested from the network with the equivalent resource available in the cache, if there is a matching one available. The matching is done via URL and various headers, just like with normal HTTP requests.
if there is no match we fetch the resource, and we put in cache object.
*/
if (event.request.url.indexOf('/imgs/') == -1) {
//console.log('Skipping cache asset: ' + event.request.url);
return fetch(event).then((response) => { return response });
}
event.respondWith(caches.match(event.request).then(function(cachedResponse) {
// caches.match() always resolves
// but in case of success response will have value
if (cachedResponse !== undefined)
return cachedResponse;
return self.fetch_and_cache(event.request)
}));
});