Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,17 @@
</head>

<body>

<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('./sw.js')
.then(reg => console.log('Offline modus geactiveerd!'))
.catch(err => console.error('Offline modus mislukt:', err));
});
}
</script>

</body>

</html>
47 changes: 47 additions & 0 deletions sw.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
const GHPATH = '/zainojdaf/web-dashers.github.io';
const CACHE_NAME = 'web-dashers-dynamic-v1';

const INITIAL_CORE = [
`${GHPATH}/`,
`${GHPATH}/index.html`
];

self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
return cache.addAll(INITIAL_CORE);
})
);
});

self.addEventListener('fetch', (event) => {
// (files, audio, scripts)
if (event.request.method !== 'GET') return;

event.respondWith(
caches.match(event.request).then((cachedResponse) => {
// if the file is loaded it works offline :)
if (cachedResponse) {
return cachedResponse;
}

return fetch(event.request).then((networkResponse) => {
// Test if the request works (this is important)
if (!networkResponse || networkResponse.status !== 200 || networkResponse.type !== 'basic') {
return networkResponse;
}

// makes a copy of the file (thats how it works offline heh)
const responseToCache = networkResponse.clone();
caches.open(CACHE_NAME).then((cache) => {
cache.put(event.request, responseToCache);
});

return networkResponse;
}).catch(() => {
// Fallback if you are offline and you dont have ANY files loaded
return caches.match(`${GHPATH}/index.html`);
});
})
);
});