Began Setup of Service Worker

Add js file for Service Worker to begin process of caching files for offline mode.
This commit is contained in:
2018-11-09 13:30:27 -05:00
parent 8425f6e59e
commit ff965e94d5
2 changed files with 79 additions and 0 deletions

View File

@@ -185,6 +185,20 @@
</div>
</div>
<!-- Checks is there is a service worker and adds or updates -->
<!-- <script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('sw.js')
.then(swReg => {
console.log('Service Worker is registered', swReg);
})
.catch(err => {
console.error('Service Worker Error', err);
});
});
}
</script> -->
<!-- <script src="js/vendor/modernizr-3.5.0.min.js"></script> -->
<script>window.jQuery || document.write('<script src="js/vendor/jquery-3.2.1.min.js"><\/script>')</script>

65
sw.js Normal file
View File

@@ -0,0 +1,65 @@
const filesToCache = [
'/',
'style/main.css',
'images/still_life_medium.jpg',
'index.html',
'pages/offline.html',
'pages/404.html'
];
const staticCacheName = 'pages-cache-v1';
self.addEventListener('install', event => {
console.log('Attempting to install service worker and cache static assets');
event.waitUntil(
caches.open(staticCacheName)
.then(cache => {
return cache.addAll(filesToCache);
})
);
});
self.addEventListener('fetch', event => {
console.log('Fetch event for ', event.request.url);
event.respondWith(
caches.match(event.request)
.then(response => {
if (response) {
console.log('Found ', event.request.url, ' in cache');
return response;
}
console.log('Network request for ', event.request.url);
return fetch(event.request)
.then(response => {
// TODO 5 - Respond with custom 404 page
return caches.open(staticCacheName).then(cache => {
cache.put(event.request.url, response.clone());
return response;
});
});
}).catch(error => {
// TODO 6 - Respond with custom offline page
})
);
});
self.addEventListener('activate', event => {
console.log('Activating new service worker...');
const cacheWhitelist = [staticCacheName];
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (cacheWhitelist.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
}
})
);
})
);
});