This commit is contained in:
Kasper Rynning-Tønnesen
2016-08-03 10:29:19 +02:00
parent 204b067e67
commit 4359144925
4 changed files with 39 additions and 133 deletions

View File

@@ -1,5 +1,3 @@
//importScripts('/static/dist/lib/cache-polyfill.js');
var version = 'v2.1'; var version = 'v2.1';
var CACHE_FILES = [ var CACHE_FILES = [
'https://chart.googleapis.com/chart?chs=150x150&cht=qr&chl=https://zoff.no/&choe=UTF-8&chld=L%7C1', 'https://chart.googleapis.com/chart?chs=150x150&cht=qr&chl=https://zoff.no/&choe=UTF-8&chld=L%7C1',
@@ -57,7 +55,6 @@ self.addEventListener("activate", function(event) {
var cacheWhitelist = version; var cacheWhitelist = version;
event.waitUntil( event.waitUntil(
caches.keys().then(function(keyList) { caches.keys().then(function(keyList) {
return Promise.all(keyList.map(function(key) { return Promise.all(keyList.map(function(key) {
@@ -97,126 +94,31 @@ self.addEventListener("activate", function(event) {
*/ */
}); });
self.addEventListener("fetch", function(event) { self.addEventListener('fetch', event => {
//console.log('WORKER: fetch event in progress.'); // We only want to call event.respondWith() if this is a navigation request
// for an HTML page.
/* We should only cache GET requests, and deal with the rest of method in the // request.mode of 'navigate' is unfortunately not supported in Chrome
client-side, by handling failed POST,PUT,PATCH,etc. requests. // versions older than 49, so we need to include a less precise fallback,
*/ // which checks for a GET request with an Accept: text/html header.
if (event.request.method !== 'GET') { if (event.request.mode === 'navigate' ||
/* If we don't block the event as shown below, then the request will go to (event.request.method === 'GET' &&
the network as usual. event.request.headers.get('accept').includes('text/html'))) {
*/
//console.log('WORKER: fetch event ignored.', event.request.method, event.request.url);
return;
}
/* Similar to event.waitUntil in that it blocks the fetch event on a promise.
Fulfillment result will be used as the response, and rejection will end in a
HTTP response indicating failure.
*/
event.respondWith( event.respondWith(
caches fetch(event.request.url).catch(error => {
/* This method returns a promise that resolves to a cache entry matching // The catch is only triggered if fetch() throws an exception, which will most likely
the request. Once the promise is settled, we can then provide a response // happen due to the server being unreachable.
to the fetch request. // If fetch() returns a valid HTTP response with an response code in the 4xx or 5xx
*/ // range, the catch() will NOT be called. If you need custom handling for 4xx or 5xx
.match(event.request) // errors, see https://github.com/GoogleChrome/samples/tree/gh-pages/service-worker/fallback-response
.then(function(cached) { return caches.open(version + "::bare").then(function(cache) {
/* Even if the response is in our cache, we go to the network as well. return cache.match('/static/offline/offline.html');
This pattern is known for producing "eventually fresh" responses, });
where we return cached responses immediately, and meanwhile pull })
a network response and store that in the cache. );
Read more: }
https://ponyfoo.com/articles/progressive-networking-serviceworker
*/
var networked = fetch(event.request)
// We handle the network request with success and failure scenarios.
.then(fetchedFromNetwork, unableToResolve)
// We should catch errors on the fetchedFromNetwork handler as well.
.catch(unableToResolve);
/* We return the cached response immediately if there is one, and fall // If our if() condition is false, then this fetch handler won't intercept the request.
back to waiting on the network as usual. // If there are any other fetch handlers registered, they will get a chance to call
*/ // event.respondWith(). If no fetch handlers call event.respondWith(), the request will be
//console.log('WORKER: fetch event', cached ? '(cached)' : '(network)', event.request.url); // handled by the browser as if there were no service worker involvement.
return cached || networked;
function fetchedFromNetwork(response) {
/* We copy the response before replying to the network request.
This is the response that will be stored on the ServiceWorker cache.
*/
var cacheCopy = response.clone();
//console.log('WORKER: fetch response from network.', event.request.url);
//console.log(event.request.url == "http://localhost/");
caches
// We open a cache to store the response for this request.
.open(version + '::plus')
.then(function add(cache) {
/* We store the response for this request. It'll later become
available to caches.match(event.request) calls, when looking
for cached responses.
*/
if(event.request.url.indexOf(":8880") == -1 &&
event.request.url.indexOf("img.youtube.com/vi/") == -1 &&
event.request.url.indexOf("static/images/thumbnails") == -1 &&
event.request.url.indexOf("chart.googleapis") == -1 &&
event.request.url != "https://zoff.no/" &&
event.request.url != "http://localhost/" &&
event.request.url.indexOf("googleapis.com/youtube/v3") == -1 &&
event.request.url.indexOf("google-analytics.com/") == -1 &&
event.request.url.indexOf("google-analytics.com/") == -1 &&
event.request.url.indexOf("i.ytimg.com") == -1 &&
event.request.url.indexOf("php/") == -1 &&
event.request.url.indexOf("/static/") == -1 &&
event.request.url.indexOf("https://zoff.no/") == -1 &&
event.request.url.indexOf("http://localhost/") == -1 &&
event.request.url.indexOf("cdn.socket.io") == -1) {
cache.put(event.request, cacheCopy);
}
})
.then(function() {
//console.log('WORKER: fetch response stored in cache.', event.request.url);
});
// Return the response so that the promise is settled in fulfillment.
return response;
}
/* When this method is called, it means we were unable to produce a response
from either the cache or the network. This is our opportunity to produce
a meaningful response even when all else fails. It's the last chance, so
you probably want to display a "Service Unavailable" view or a generic
error response.
*/
function unableToResolve () {
/* There's a couple of things we can do here.
- Test the Accept header and then return one of the `offlineFundamentals`
e.g: `return caches.match('/some/cached/image.png')`
- You should also consider the origin. It's easier to decide what
"unavailable" means for requests against your origins than for requests
against a third party, such as an ad provider
- Generate a Response programmaticaly, as shown below, and return that
*/
//console.log('WORKER: fetch request failed in both cache and network.');
/* Here we're creating a response programmatically. The first parameter is the
response body, and the second one defines the options for the response.
*/
/*return new Response('<h1>Zöff is currently unavailable, sorry</h1>', {
status: 503,
statusText: 'Service Unavailable',
headers: new Headers({
'Content-Type': 'text/html'
})
});*/
return caches.open(version + "fundamentals").then(function(cache) {
return cache.match('/static/offline/offline.html');
});
}
})
);
}); });

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -60,13 +60,17 @@ var connection_options = {
var fromFront = false; var fromFront = false;
var fromChannel = false; var fromChannel = false;
if ('serviceWorker' in navigator) { if (navigator.serviceWorker) {
navigator.serviceWorker.getRegistration().then(function(r) { navigator.serviceWorker.register('/service-worker.js', {scope: '/'})
try { .then(function (registration) {
r.unregister(); console.log(registration);
} catch(e) {} })
}); .catch(function (e) {
}; console.error(e);
})
} else {
console.log('Service Worker is not supported in this browser.');
}
$().ready(function(){ $().ready(function(){
if(!fromFront && window.location.pathname != "/") init(); if(!fromFront && window.location.pathname != "/") init();