Skip to content

Instantly share code, notes, and snippets.

@prof3ssorSt3v3
Created March 9, 2021 21:50
Show Gist options
  • Select an option

  • Save prof3ssorSt3v3/bde9122fbc7819d8ff328916bd3161e7 to your computer and use it in GitHub Desktop.

Select an option

Save prof3ssorSt3v3/bde9122fbc7819d8ff328916bd3161e7 to your computer and use it in GitHub Desktop.
Code from Service Workers 3 - self.skipWaiting, ev.waitUntil, and clients.claim
const APP = {
SW: null,
init() {
//called after DOMContentLoaded
//register the service worker
APP.registerSW();
//add click listener for h2 to load a new image
document.querySelector('h2').addEventListener('click', APP.addImage);
},
registerSW() {
if ('serviceWorker' in navigator) {
// Register a service worker hosted at the root of the site
navigator.serviceWorker.register('/sw.js').then(
(registration) => {
APP.SW =
registration.installing ||
registration.waiting ||
registration.active;
},
(error) => {
console.log('Service worker registration failed:', error);
}
);
} else {
console.log('Service workers are not supported.');
}
},
addImage(ev) {
let img = document.createElement('img');
img.src = '/img/1016-800x600.jpg';
img.alt = 'dynamically added image';
let p = document.createElement('p');
p.append(img);
document.querySelector('main').append(p);
},
};
document.addEventListener('DOMContentLoaded', APP.init);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Intro to Service Workers</title>
<!-- import google fonts -->
<link rel="preconnect" href="https://fonts.gstatic.com" />
<link
href="https://fonts.googleapis.com/css2?family=Montserrat:wght@200;500;700&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="css/main.css" />
</head>
<body>
<header>
<h1>Intro to Service Workers</h1>
<h2>self.skipWaiting(), ev.waitUntil(), and clients.claim()</h2>
</header>
<!--
Images from:
-->
<main>
<p>
<img src="/img/1011-800x600.jpg" alt="sample image 1" />
</p>
<!-- <p>
<img src="/img/1016-800x600.jpg" alt="sample image 2" />
</p> -->
</main>
<script defer src="./js/app.js"></script>
</body>
</html>
html {
font-size: 20px;
font-family: 'Montserrat', sans-serif;
line-height: 1.5;
background-color: #222;
color: #eee;
}
body {
min-height: 100vh;
background-color: inherit;
color: inherit;
}
header,
main {
margin: 1rem 2rem;
}
main {
display: flex;
flex-direction: row;
flex-wrap: wrap;
gap: 1rem;
justify-content: space-around;
}
h1 {
color: orangered;
}
h2 {
color: orange;
}
main img {
/* max-width: 100%;
min-width: 200px; */
width: clamp(200px, 400px, 600px);
}
const version = 1;
self.addEventListener('install', (ev) => {
//service worker has been installed.
//Extendable Event
ev.waitUntil(
Promise.resolve()
.then(() => {
manuel();
})
.then(() => {
//the promise returned from teja will wait until it resolves
//before going to the next then()
return teja();
})
.then(() => {
console.log('installed');
//when this then() returns undefiined
//it goes to the ev.waitUntil
//which will change our state from installing to installed.
})
);
// self.skipWaiting(); //skip waiting to activate
//but... the page will not use the new sw yet
});
function teja() {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('teja');
resolve();
}, 2000);
});
}
function manuel() {
console.log('manuel');
}
self.addEventListener('activate', (ev) => {
// when the service worker has been activated to replace an old one.
//Extendable Event
console.log('activated - this worker not used until page reloads');
// clients.claim().then(() => {
// //claim means that the html file will use this new service worker.
// console.log(
// 'the service worker has now claimed all pages so they use the new service worker.'
// );
// });
});
self.addEventListener('fetch', (ev) => {
// ev.request each time the webpage asks for any resource.
//Extendable Event
console.log('fetch request for', ev.request.url, 'from', ev.clientId);
//check the cache then do a fetch if missing
});
self.addEventListener('message', (ev) => {
//message from web page ev.data.
//Extendable Event
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment