Skip to content

Instantly share code, notes, and snippets.

@surma
Created March 29, 2016 10:37
Show Gist options
  • Save surma/af54d2d23ac18cfb544e to your computer and use it in GitHub Desktop.
Save surma/af54d2d23ac18cfb544e to your computer and use it in GitHub Desktop.
Populate Cache from client side
Hello World
<button>Load me</button>
<div></div>
<script>
var $ = document.querySelector.bind(document);
navigator.serviceWorker.register('sw.js').then(registration => {
fetch('/data.txt').then(response => {
return caches.open('test').then(cache => {
return cache.put('/data.txt', response);
});
});
});
$('button').addEventListener('click', _ => {
fetch('/data.txt')
.then(response => response.text())
.then(response => $('div').innerText = response);
});
</script>
self.addEventListener('install', function(event) {
event.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', function(event) {
event.waitUntil(self.clients.claim());
});
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(response => response || fetch(event.request))
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment