55 lines
1.3 KiB
JavaScript
55 lines
1.3 KiB
JavaScript
const assets = ["<@ASSETS@>"];
|
|
|
|
const staticCacheName = "tytd-static-<@BUILD_TIME@>";
|
|
|
|
async function ThrowOnBadGateway(req)
|
|
{
|
|
const resp = await fetch(req);
|
|
if(resp.status === 502) throw new Error("Bad Gateway");
|
|
return resp;
|
|
}
|
|
|
|
self.addEventListener('install',evt => {
|
|
evt.waitUntil(
|
|
caches.open(staticCacheName).then(cache =>{
|
|
cache.addAll(assets);
|
|
})
|
|
);
|
|
});
|
|
|
|
self.addEventListener('activate',(evt)=>{
|
|
evt.waitUntil(
|
|
caches.keys().then(keys => {
|
|
return Promise.all(keys.filter(key => key !== staticCacheName).map(key => caches.delete(key)));
|
|
})
|
|
);
|
|
});
|
|
|
|
self.addEventListener('fetch', evt => {
|
|
|
|
evt.respondWith(
|
|
|
|
caches.match(evt.request).then(cacheRes=>{
|
|
console.warn('SW cacheRes:', cacheRes);
|
|
return cacheRes || ThrowOnBadGateway(evt.request);
|
|
}).catch((err)=>{
|
|
console.warn('SW Fallback:', err.message);
|
|
if(evt.request.headers.has('HX-Request'))
|
|
{
|
|
|
|
return new Response("",{
|
|
status: 200,
|
|
headers: {
|
|
'HX-Redirect': "/offline.html"
|
|
}
|
|
});
|
|
}
|
|
else
|
|
{
|
|
return caches.match('/offline.html');
|
|
|
|
}
|
|
})
|
|
);
|
|
});
|