Skip to content

Instantly share code, notes, and snippets.

@lazy-sunshine
Created August 14, 2020 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lazy-sunshine/6ffe42ba20479b72bba62933675548a1 to your computer and use it in GitHub Desktop.
Save lazy-sunshine/6ffe42ba20479b72bba62933675548a1 to your computer and use it in GitHub Desktop.
Service File
let urlToAdd =[
'./style.css',
'./wallpaper.jpg',
'./offline.html'
]
self.addEventListener('install', (event) => {
event.waitUntill(
caches.open('SERVICE_WORKER')
.then((cache)=>{
console.log('cache openend');
return cache.addAll(urlToAdd);
})
.catch(err => {
console.log(err);
})
)
});
self.addEventListener('fetch', (event)=>{
console.log('fetch event');
if (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html')) {
event.respondWith(
fetch(event.request.url).catch(error => {
// Return the offline page
return caches.match('./offline.html');
})
);
}
else{
event.respondWith(
caches.match(event.request)
.then((response)=>{
if(response) return response;
return fetch(event.request);
})
)
}
});
self.addEventListener('activate', (event)=>{
const whiteList =['SERVICE_WORKER','my-page'];
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(cacheName) {
if (whiteList.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
}
})
);
})
);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment