javascript - Service worker offline support with pushstate and client side routing -


i'm using service worker introduce offline functionality single page web app. it's pretty straightforward - use network when available, or try , fetch cache if not:

service-worker.js:

self.addeventlistener("fetch", event => {     if(event.request.method !== "get") {         return;     }     event.respondwith(         fetch(event.request)             .then(networkresponse => {                 var responseclone = networkresponse.clone();                 if (networkresponse.status == 200) {                     caches.open("mycache").then(cache => cache.put(event.request, responseclone));                 }             return networkresponse;         })         .catch(_ => {             return caches.match(event.request);         })     ) }) 

so intercepts requests , caches them future use, including initial page load.

switching "offline" in devtools , refreshing @ root of application works expected.

however, app uses html5 pushstate , client side router. user navigate new route, go offline, hit refresh, , "no internet" message, because service worker never told new url.

i can't think of way around it. spas, server configured serve index.html number of catch-all urls. need sort of similar behaviour service worker.

inside fetch handler, need check whether event.request.mode set 'navigate'. if so, it's navigation, , instead of responding cached response matches specific url, can respond cached response index.html. (or app-shell.html, or whatever url use generic html spa.)

your updated fetch handler like:

self.addeventlistener('fetch', event => {   if (event.request.method !== 'get') {     return;   }    if (event.request.mode === 'navigate') {     event.respondwith(caches.match('index.html'));     return;   }    // rest of fetch handler logic goes here. }); 

this common use case service workers, , if you'd prefer use pre-packaged solution, navigationroute class in workbox-routing module can automate you.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -