Last active
January 25, 2023 16:21
-
-
Save bryandh/c22a39f22395f155123b6b82fcd5f438 to your computer and use it in GitHub Desktop.
Service Worker setup in Typescript
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
function registerServiceWorker(): void { | |
if ('serviceWorker' in navigator) { | |
navigator.serviceWorker.register('/src/service-worker.js') | |
.then((registration) => | |
console.log(`Service Worker registration complete, scope: '${registration.scope}'`)) | |
.catch((error) => | |
console.log(`Service Worker registration failed with error: '${error}'`)); | |
} | |
} | |
registerServiceWorker(); |
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
class ServiceWorkerOne { | |
public static run(): void { | |
addEventListener('install', ServiceWorkerOne.onInstalled); | |
addEventListener('fetch', ServiceWorkerOne.onFetched); | |
} | |
public static onInstalled = (event: any): void => { | |
event.waitUntil( | |
caches.open('v0.1').then((cache) => { | |
return cache.addAll([ | |
'/scripts/app-bundle.js', | |
'/scripts/vendor-bundle.js', | |
'/assets/images/logo.png', | |
'/assets/images/no-vessel-picture.jpg', | |
'/assets/styles/loader.css', | |
'/assets/scripts/fontawesome-pro/css/fa-svg-with-js.css', | |
'/assets/scripts/fontawesome-pro/js/fontawesome.min.js', | |
'/assets/scripts/fontawesome-pro/js/fa-light.min.js', | |
'/assets/scripts/fontawesome-pro/js/fa-regular.min.js', | |
'/assets/scripts/fontawesome-pro/js/fa-solid.min.js' | |
]); | |
}) | |
); | |
} | |
public static onFetched = (event: any): void => { | |
event.respondWith( | |
caches.match(event.request).then((matchResponse) => { | |
return matchResponse || fetch(event.request).then((fetchResponse) => { | |
return caches.open('v0.1').then((cache) => { | |
cache.put(event.request, fetchResponse.clone()); | |
return fetchResponse; | |
}); | |
}); | |
}) | |
); | |
} | |
} | |
ServiceWorkerOne.run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello! Nice approach.
What would be the content of service-worker.js file?
Thanks!