Browse Source

testing a service worker

master
Clark Wimberly 2 years ago
parent
commit
77bc135c0a
2 changed files with 79 additions and 0 deletions
  1. +17
    -0
      _includes/head.html
  2. +62
    -0
      serviceworker.js

+ 17
- 0
_includes/head.html View File

@ -22,6 +22,23 @@
<meta name="msapplication-TileColor" content="#007fff">
<meta name="msapplication-config" content="{{ site.baseurl }}/icons/browserconfig.xml">
<meta name="theme-color" content="#007fff">
<script>
if ("serviceWorker" in navigator) {
if (navigator.serviceWorker.controller) {
console.log("An active service worker found, no need to register");
} else {
// Register the service worker
navigator.serviceWorker
.register("{{ site.baseurl }}/serviceworker.js", {
scope: "./"
})
.then(function (reg) {
console.log("Service worker has been registered for scope: " + reg.scope);
});
}
}
</script>
<!-- Twitter Cards -->
<meta name="twitter:card" content="summary_large_image">


+ 62
- 0
serviceworker.js View File

@ -0,0 +1,62 @@
const CACHE = "pwabuilder-offline";
const offlineFallbackPage = "index.html";
// Install stage sets up the index page (home page) in the cache and opens a new cache
self.addEventListener("install", function (event) {
console.log("Install Event processing");
event.waitUntil(
caches.open(CACHE).then(function (cache) {
console.log("Cached offline page during install");
if (offlineFallbackPage === "ToDo-replace-this-name.html") {
return cache.add(new Response("Update the value of the offlineFallbackPage constant in the serviceworker."));
}
return cache.add(offlineFallbackPage);
})
);
});
// If any fetch fails, it will look for the request in the cache and serve it from there first
self.addEventListener("fetch", function (event) {
if (event.request.method !== "GET") return;
event.respondWith(
fetch(event.request)
.then(function (response) {
console.log("Add page to offline cache: " + response.url);
// If request was success, add or update it in the cache
event.waitUntil(updateCache(event.request, response.clone()));
return response;
})
.catch(function (error) {
console.log("Network request Failed. Serving content from cache: " + error);
return fromCache(event.request);
})
);
});
function fromCache(request) {
// Check to see if you have it in the cache
// Return response
// If not in the cache, then return error page
return caches.open(CACHE).then(function (cache) {
return cache.match(request).then(function (matching) {
if (!matching || matching.status === 404) {
return Promise.reject("no-match");
}
return matching;
});
});
}
function updateCache(request, response) {
return caches.open(CACHE).then(function (cache) {
return cache.put(request, response);
});
}

Loading…
Cancel
Save