Service Worker Offline Status

Introduction

Challenges

Setup and Installation

if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/service-worker.js').then(function(registration) {
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}, function(err) {
console.log('ServiceWorker registration failed: ', err);
});
});
}

Service Worker JavaScript Notes

The Service Worker JavaScript

var CACHE_NAME = "htt-cache-v007";
var OFFLINE_URL = "/offline";
var REQUIRED_FILES = [
"/offline",
"/app.min.css",
"/app.min.js",
"/favicons/android-chrome-192x192.png",
"/favicons/android-chrome-512x512.png",
"/favicons/apple-touch-icon.png",
"/favicons/browserconfig.xml",
"/favicons/favicon-16x16.png",
"/favicons/favicon-32x32.png",
"/favicons/favicon.ico",
"/favicons/manifest.json",
"/favicons/mstile-150x150.png",
"/favicons/safari-pinned-tab.svg",
"/media/logo.png"
];
self.addEventListener('install', function(event) {
event.waitUntil(caches.open(CACHE_NAME).then(function(cache) {
return Promise.all(REQUIRED_FILES.map(function(url) {
return fetch(new Request(url, { redirect: 'manual' })).then(function(res) {
return cache.put(url, res);
});
}));
}));
});
self.addEventListener('fetch', function(event) {
if (event.request.mode === 'navigate' || (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
if(event.request.url.includes("your-domain-name.com")){
event.respondWith (
caches.match (event.request, {cacheName: CACHE_NAME}).then(function(resp) {
return resp || fetch(event.request).then(function(response) {
let responseClone = response.clone();
caches.open(CACHE_NAME).then(function(cache) {
cache.put(event.request, responseClone);
});
return response;
});
}).catch(function(error) {
return caches.open(CACHE_NAME).then(function (cache) {
return cache.match(OFFLINE_URL);
});
})
);
}
}
});
self.addEventListener('activate', function(event) {
var cacheWhitelist = [CACHE_NAME];
event.waitUntil(
caches.keys().then(function(keyList) {
return Promise.all(keyList.map(function(key) {
if (cacheWhitelist.indexOf(key) === -1) {
console.log('Deleting out of date cache:', CACHE_NAME);
return caches.delete(key);
}
}));
})
);
});

Troubleshooting

--

--

Delivering refined solutions via vigorous practice. Tulane ('97), Cisco CCIE# 6824, Google Certified Professional Cloud Architect, and USPA Master Skydiver

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ronnie Royston

Delivering refined solutions via vigorous practice. Tulane ('97), Cisco CCIE# 6824, Google Certified Professional Cloud Architect, and USPA Master Skydiver