Skip to content

Commit

Permalink
started PWA
Browse files Browse the repository at this point in the history
  • Loading branch information
NwinNwin committed Feb 22, 2024
1 parent 173c9f1 commit 5bfe132
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
17 changes: 17 additions & 0 deletions public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -113,5 +113,22 @@
id="root"
style="height: 100vh; position: fixed; top: 0; width: 100%"
></div>
<script>
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);
}
);
});
}
</script>
</body>
</html>
38 changes: 38 additions & 0 deletions public/serviceWorker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const CACHE_NAME = "version-1";
const urlsToCache = ["index.html", "offline.html"];

this.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
console.log("Opened cache");
return cache.addAll(urlsToCache);
})
);
});

this.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request).then((response) => {
if (response) {
return response;
}
return fetch(event.request).catch(() => caches.match("offline.html"));
})
);
});

this.addEventListener("activate", (event) => {
const cacheWhitelist = [];
cacheWhitelist.push(CACHE_NAME);
event.waitUntil(
caches.keys().then((cacheNames) =>
Promise.all(
cacheNames.map((cacheName) => {
if (!cacheWhitelist.includes(cacheName)) {
return caches.delete(cacheName);
}
})
)
)
);
});

0 comments on commit 5bfe132

Please sign in to comment.