-
-
Save onigetoc/b56ed7a8aca0bafd9bdc832308ff49f6 to your computer and use it in GitHub Desktop.
Service Workers
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
/** | |
* If there are service workers available to us, then on window load we can register our worker | |
*/ | |
'serviceWorker' in navigator && window.addEventListener('load', () => { | |
navigator.serviceWorker.register('worker.js') | |
.then(() => { | |
// Registration was successful | |
console.log('ServiceWorker registration successful!'); | |
}, (err) => { | |
// registration failed :( | |
console.log('ServiceWorker registration failed: ', err); | |
}); | |
}); |
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
// Fires when the browser trys to fetch any asset | |
self.addEventListener('fetch', (event) => { | |
event.respondWith( | |
// check if the asset is one we are saving/watching | |
caches.match(event.request).then((eventRequest) => { | |
return eventRequest || fetch(event.request).then((response) => { | |
// try to open the cache, but fall back on the request if we can't open the cache | |
return caches.open(CACHE_NAME) | |
.then((cache) => { | |
// replace the request with the cache's content | |
cache.put(event.request, response.clone()); | |
return response; | |
}); | |
}); | |
}); | |
); | |
}); |
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
// This gets updated on new builds! | |
const CACHE_NAME = `Cache_${__SERVICE_WORKER_V__}`; | |
const urlsToCache = [ | |
... | |
]; | |
// Perform install steps of adding all defined assets to the cache | |
self.addEventListener('install', (event) => { | |
event.waitUntil( | |
caches.open(CACHE_NAME) | |
.then(cache => cache.addAll(urlsToCache)); | |
); | |
}); | |
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
const webpack = require('webpack'); | |
module.exports = { | |
// ... | |
plugins: [ | |
// This is for auto updating the service worker version on builds | |
new webpack.DefinePlugin({ | |
__SERVICE_WORKER_V__: Date.now() | |
}) | |
], | |
// ... | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment