Skip to content

Commit 7e31b71

Browse files
authored
Merge pull request #64 from satyam-seth-learnings/service-worker-api
Add service worker api demo
2 parents fa75d28 + 5cbe093 commit 7e31b71

File tree

6 files changed

+59
-0
lines changed

6 files changed

+59
-0
lines changed

Service Worker API/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
[MDN Doc Link](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers)
2+
3+
[MDN Example Link](https://github.dev/mdn/dom-examples/tree/main/service-worker/simple-service-worker)

Service Worker API/demo.html

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
6+
<link rel="stylesheet" href="style.css">
7+
<title>Service Worker API</title>
8+
</head>
9+
<body>
10+
<button id="sw-register">Register Service Worker</button>
11+
<script src="script.js"></script>
12+
</body>
13+
</html>

Service Worker API/image.png

523 KB
Loading

Service Worker API/script.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
async function registerServiceWorker() {
2+
if ("serviceWorker" in navigator) {
3+
try {
4+
const registration = await navigator.serviceWorker.register("/Service Worker API/sw.js", {
5+
scope: "/Service Worker API/",
6+
});
7+
if (registration.installing) {
8+
console.log("Service worker installing");
9+
} else if (registration.waiting) {
10+
console.log("Service worker installed");
11+
} else if (registration.active) {
12+
console.log("Service worker active");
13+
}
14+
} catch (error) {
15+
console.error(`Registration failed with ${error}`);
16+
}
17+
}
18+
};
19+
20+
window.onload = function () {
21+
const registerSwBtn = document.getElementById('sw-register');
22+
registerSwBtn.addEventListener('click', registerServiceWorker);
23+
}

Service Worker API/style.css

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
body {
2+
background-color: black;
3+
}

Service Worker API/sw.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
const addResourcesToCache = async (resources) => {
2+
const cache = await caches.open('v1');
3+
await cache.addAll(resources);
4+
};
5+
6+
7+
// Install and activate: populating your cache
8+
self.addEventListener('install', (event) => {
9+
event.waitUntil(
10+
addResourcesToCache([
11+
'/Service Worker API/demo.html',
12+
'/Service Worker API/style.css',
13+
'/Service Worker API/script.js',
14+
'/Service Worker API/image.png',
15+
])
16+
);
17+
});

0 commit comments

Comments
 (0)