working example: to document it

This commit is contained in:
Amber 2020-11-27 12:04:09 +01:00
parent 1b980766ff
commit c208c7415b
3 changed files with 33 additions and 98 deletions

View File

@ -25,14 +25,11 @@ self.addEventListener('install', (event) => {
The request objects created during retrieval become keys to the stored response operations.
*/
return cache.addAll([
//'/',
//'/css/materialize.css',
//'/index.html',
'/imgs/180295.jpg',
'/imgs/180343.jpg',
'/imgs/180401.jpg',
'/imgs/1920x1200-Linux Widescreen705729403.jpg',
'/imgs/2551508.jpg'
//'/imgs/180295.jpg',
//'/imgs/180343.jpg',
//'/imgs/180401.jpg',
//'/imgs/1920x1200-Linux Widescreen705729403.jpg',
//'/imgs/2551508.jpg'
]);
}));
@ -55,17 +52,19 @@ self.addEventListener('install', (event) => {
*
*
*/
/*
self.fetch_and_cache = function (evreq) {
fetch(evreq).then((response) => {
return caches.open('v1').then((cache) => {
cache.put(evreq, request.clone());
console.log('fetch and cache ' + evreq);
cache.put(evreq, response.clone());
return response
}).catch(() => {
console.log('___ here a callback ___');
});
});
}
*/
/**
*
@ -85,11 +84,27 @@ self.addEventListener('fetch', (event) => {
if there is no match we fetch the resource, and we put in cache object.
*/
console.log('Handling fetch event for', event.request.url);
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((response) => {
if (response !== 'undefined') return response
return self.fetch_and_cache(event.request);
}));
})
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 fetch(event.request).then(function (response) {
// response may be used only once
// we need to save clone to put one copy in cache
// and serve second one
let responseClone = response.clone();
caches.open('v1').then(function (cache) {
cache.put(event.request, responseClone);
});
return response;
});
}));
});

View File

@ -52,7 +52,7 @@
*/
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./cachersw.js', {scope: '/imgs'})
navigator.serviceWorker.register('/cachersw.js', {scope: '/'})
.then((reg) => {
// registration worked
console.log('Registration succeeded. Scope is ' + reg.scope);

View File

@ -1,80 +0,0 @@
/*
*
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'
]);
}));
});
/**
*
*
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.
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
*/
event.respondWith(
caches.match(event.request).then((response) => {
if (response) return response
fetch(event.request).then((response) => {
return caches.open('v1').then((cache) => {
cache.put(event.request, request.clone());
return response
}).catch(() => {
console.log('___ here a callback ___');
});
});
}));
})