How to enable offline support when using HTML5 history api
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
:
- the precacheConfig Array contains
['/index.html', ...]
- 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.