-->

How to enable offline support when using HTML5 his

2019-04-15 09:08发布

问题:

What are the best practices (and how to go about doing it) to support offline mode when using html5 history api for url rewrites?

For example, (hypothetically) I have a PWA SPA application at https://abc.xyz which has internationalization built in. So when I visit this link, the Vue router (which ideally could be any framework - vue, react, angular etc.) redirect me to https://abc.xyz/en.

This works perfectly when I am online (ofcourse, the webserver is also handling this redirect so that app works even if you directly visit the said link).

However, its a different story when I am offline. The service worker caches all resources correctly so when I visit the URL https://abc.xyz everything loads up as expected. However, now if I manually type the URL to https://abc.xyz/en, the app fails to load up.

Any pointers on how to achieve this?

Link to same question in github: https://github.com/vuejs-templates/pwa/issues/188

回答1:

Yes, this is possible quite trivially with Service Workers. All you have to do is to configure the navigateFallback property of sw-precache properly. It has to point to the cached asset you want the service worker to fetch if it encounters a cache miss.

In the template you posted, you should be good to go if you configure your SWPrecache Webpack Plugin as follows:

new SWPrecacheWebpackPlugin({
    ...
    navigateFallback: '/index.html'
    ...
})

Again, it is absolutely mandatory that the thing you put inside navigateFallback is cached by the Service Worker already, otherwise this will fail silently.

You can verify if everything was configured correctly by checking two things in your webpack generated service-worker.js:

  1. the precacheConfig Array contains ['/index.html', ...]
  2. in the fetch interceptor of the service worker (at the bottom of the file), the variable navigateFallback is set to the value you configured

If your final App is hosted in a subdirectory, for example when hosting it on Github pages, you also have to configure the stripPrefix and replacePrefix Options correctly.