Skip to content

Instantly share code, notes, and snippets.

@prof3ssorSt3v3
Last active August 22, 2024 12:33
Show Gist options
  • Select an option

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

Select an option

Save prof3ssorSt3v3/cdcc405fca814a3e39825a17cf2b6c82 to your computer and use it in GitHub Desktop.
Code from Service Workers 4 - integrating the cache api with a service worker
const APP = {
SW: null,
init() {
//called after DOMContentLoaded
APP.registerSW();
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>Controlling Caches with a Service Worker</h2>
</header>
<!--
IMAGES
https://picsum.photos/id/1011/5472/3648
https://picsum.photos/id/1016/3844/2563
-->
<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 = 5;
let staticName = `staticCache-${version}`;
let dynamicName = `dynamicCache`;
let fontName = 'fontCache';
let imgName = 'imageCache';
let assets = ['/', '/index.html', '/css/main.css', '/js/app.js'];
self.addEventListener('install', (ev) => {
// service worker has been installed.
//Extendable Event
console.log(`Version ${version} installed`);
// build a cache
ev.waitUntil(
caches.open(staticName).then((cache) => {
cache.addAll(assets).then(
() => {
//addAll == fetch() + put()
console.log(`${staticName} has been updated`);
},
(err) => {
console.warn(`failed to update ${staticName}.`);
}
);
})
);
});
self.addEventListener('activate', (ev) => {
// when the service worker has been activated to replace an old one.
//Extendable Event
console.log('activated');
// delete old versions of caches.
ev.waitUntil(
caches.keys().then((keys) => {
return Promise.all(
keys.filter((key) => key != staticName).map((key) => caches.delete(key))
);
})
);
});
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