Skip to content

Commit

Permalink
Merge pull request #394 from ashawley/service-worker
Browse files Browse the repository at this point in the history
Add initial Service Worker
  • Loading branch information
ashawley authored Feb 14, 2019
2 parents e510150 + 0cdeaf3 commit 333cb69
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
5 changes: 5 additions & 0 deletions _includes/footer.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,8 @@
anchors.options.visible = 'always';
anchors.add('article h2, article h3, article h4, article h5, article h6');
</script>{% endif %}
<script type="text/javascript">
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("{{ '/sw.js' | relative_url }}")
}
</script>
54 changes: 54 additions & 0 deletions sw.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
---
layout: null
---
var CACHE_NAME = "pixyll2-{{site.time | date: '%Y%m%d%H%M%S'}}";

self.addEventListener("install", function(e) {
e.waitUntil(
caches.open(CACHE_NAME).then(function(cache) {
return cache.addAll([
"{{ '/css/pixyll.css' | relative_url }}?{{ site.time | date: '%Y%m%d%H%M' }}",
"{{ '/' | relative_url }}"
]);
})
);
});

self.addEventListener("activate", function(e) {
e.waitUntil(
caches.keys().then(function(names) {
return Promise.all(
names.map(function(name) {
if (name != CACHE_NAME) {
return caches.delete(name);
}
})
);
})
);
return clients.claim();
});

addEventListener("fetch", function(e) {
e.respondWith(
caches.match(e.request).then(function(response) {
return response || fetch(e.request).then(function(response) {
var clonedResponse = response.clone();
var hosts = [
"https://fonts.googleapis.com",
"https://fonts.gstatic.com",
"https://maxcdn.bootstrapcdn.com",
"https://cdnjs.cloudflare.com"
];
hosts.map(function(host) {
if (e.request.url.indexOf(host) === 0) {
caches.open(CACHE_NAME).then(function(cache) {
cache.put(e.request, clonedResponse);
});
}
});
return response;
});
})
);
});

0 comments on commit 333cb69

Please sign in to comment.