Skip to content

Instantly share code, notes, and snippets.

View osvaldasvalutis's full-sized avatar

Osvaldas Valutis osvaldasvalutis

View GitHub Profile
// a check if the technology is supported by browser
if('serviceWorker' in navigator) {
navigator.serviceWorker.register('/serviceworker.js');
}
if('serviceWorker' in navigator) {
document.querySelector('.hero').addEventListener('animationend', function () {
// service worker is registered only when the animation ends
navigator.serviceWorker.register('/serviceworker.js');
});
}
// ---
App.init({
// config
complete: function() {
if('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/serviceworker.js');
});
}
self.addEventListener('install', event => {
// ...
});
self.addEventListener('activate', event => {
// ...
});
self.addEventListener('fetch', event => {
// ...
});
const criticalResources = [
'/',
'/offline/',
'/assets/css/main.css',
'/assets/js/main.js'
],
cacheCriticals = () => {
return caches.open(version).then( cache => {
return cache.addAll(criticalResources);
});
const otherResources = [
'/about/',
'/contact/',
'/services/'
],
cacheCriticals = () => {
return caches.open(version).then( cache => {
cache.addAll(otherResources); // important, but not critical resources
return cache.addAll(criticalResources); // critical resources
});
self.addEventListener('fetch', event => {
event.respondWith(
// try fetching a resource from the network
fetch(event.request).then(response => {
// cache the resource and serve it
let responseCopy = response.clone();
addToCache(event.request, responseCopy); // this is a custom function, I'll elaborate on it later
return response;
})
.catch(() => {
self.addEventListener('fetch', event => {
event.respondWith(
// check if the resource was cached before
caches.match(event.request).then(response => {
// serve the resource if cached, otherwise fetch it through the network
return response || fetch(event.request).then(response => {
// cache the newly fetched resource and serve it
let responseCopy = response.clone();
addToCache(event.request, responseCopy); // this is a custom function, I'll elaborate on it later
return response;