Created
March 29, 2016 10:37
-
-
Save surma/af54d2d23ac18cfb544e to your computer and use it in GitHub Desktop.
Populate Cache from client side
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Hello World |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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