Convert your website into a PWA

Web App Manifest

{  "name": "My first PWA",
"short_name": "PWA",
"start_url": ".",
"scope": "./",
"icons": [
{
"src": "icon.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "icon.png",
"sizes": "512x512",
"type": "image/png"
}
],
"theme_color": "#fff",
"background_color": "#333",
"display": "standalone"
}
<link rel="manifest" href="manifest.json">

Service Worker

if (navigator.serviceWorker.controller){
console.log("Service worker found")
}
else {
navigator.serviceWorker.register(‘/serviceWorker.js’)
.then(reg => console.log(‘Successfully Registered’))
.catch(err => console.log(‘Can't Register’, err));
}
let MY_CACHE = 'my-cache'
let filesToCache = [
'scripts/index.js',
'css/style.css',
'assets/images/'
]
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(MY_CACHE)
.then( (cache) => {
console.log('Opened cache')
return cache.addAll(urlsToCache)
})
.then(() =>{
console.log("Install completed")
})
)
})
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then( cacheRes => {
return cacheRes || fetch(evt.request)
}
)
);
});
let MY_CACHE = 'my-cache-v1';
let MY_DYNAMIC_CACHE = 'my-dynamic-cache-v1'
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(keys => {
return Promise.all(keys
.filter(key => key !== MY_CACHE)
.map(key => caches.delete(key))
);
})
);
});
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request).then(cacheRes => {
return cacheRes || fetch(event.request)
.then(fetchRes => {
return caches.open(MY_DYNAMIC_CACHE).then(cache => {
cache.put(event.request.url, fetchRes.clone());
return fetchRes;
})
});
})
);
});

--

--

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