Skip to content

Commit

Permalink
Add: service worker
Browse files Browse the repository at this point in the history
  • Loading branch information
mrinjamul committed Sep 2, 2021
1 parent 5451536 commit 8905c24
Show file tree
Hide file tree
Showing 4 changed files with 80 additions and 0 deletions.
10 changes: 10 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
<head>
<meta charset="UTF-8" />
<title>Start</title>
<link rel="manifest" href="manifest.json" />
<link
rel=" shortcut icon"
type="image/png"
Expand Down Expand Up @@ -103,5 +104,14 @@
<script>
feather.replace();
</script>
<script>
if (!navigator.serviceWorker.controller) {
navigator.serviceWorker.register("/sw.js").then(function (reg) {
console.log(
"Service worker has been registered for scope: " + reg.scope
);
});
}
</script>
</body>
</html>
16 changes: 16 additions & 0 deletions manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "Start",
"short_name": "Start",
"theme_color": "#2196f3",
"background_color": "#000000",
"display": "standalone",
"scope": "/",
"start_url": "/",
"orientation": "any",
"icons": [
{
"src": "assets/icons/favicon.png",
"sizes": "153x153"
}
]
}
1 change: 1 addition & 0 deletions offline.html
53 changes: 53 additions & 0 deletions sw.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
self.addEventListener("install", function (event) {
event.waitUntil(preLoad());
});

var preLoad = function () {
console.log("Installing web app");
return caches.open("offline").then(function (cache) {
console.log("caching index and important routes");
return cache.addAll(["/", "/assets", "/offline.html"]);
});
};

self.addEventListener("fetch", function (event) {
event.respondWith(
checkResponse(event.request).catch(function () {
return returnFromCache(event.request);
})
);
event.waitUntil(addToCache(event.request));
});

var checkResponse = function (request) {
return new Promise(function (fulfill, reject) {
fetch(request).then(function (response) {
if (response.status !== 404) {
fulfill(response);
} else {
reject();
}
}, reject);
});
};

var addToCache = function (request) {
return caches.open("offline").then(function (cache) {
return fetch(request).then(function (response) {
console.log(response.url + " was cached");
return cache.put(request, response);
});
});
};

var returnFromCache = function (request) {
return caches.open("offline").then(function (cache) {
return cache.match(request).then(function (matching) {
if (!matching || matching.status == 404) {
return cache.match("offline.html");
} else {
return matching;
}
});
});
};

0 comments on commit 8905c24

Please sign in to comment.