Going offline with Progressive App Development
This is the second post of the series “Going offline with Progressive Web Apps”
In the previous post, we showed an approach to offer offline support to a progressive app development, using Service Workers (SW).
This time we are going to cover other interesting aspects of an offline application, such as the web manifest and how to handle requests while offline (say Google Analytics or other API calls).
Nowadays, Service Workers are supported only in Chrome, Firefox and Opera. Therefore in this post we will cover how to use the application cache in those browsers without SW support during the progressive app development. This way we can ensure offline support for most of the browsers.
Application Cache: an alternative to cache resources
If we want our webapp to have offline support, it should be for every (or most) devices, not just for those with the latest technology. That’s part of being progressive. Fortunately, as recommended by Patrick Kettner, we can use appcache which is available in most browsers, including Safari and IE.
This technology is deprecated in favor of SW, but it will allow us to view our site when offline. It needs a manifest to tell the browser what files need to be cached. Once again, we can manually create the file following the docs, or generate it using a tool like appcache-manifest.
This command will generate it for us:
1
|
appcache-manifest 'dist/index.html' 'dist/**.js' 'dist/**.css' 'dist/images/*' --network-star -o offline/appcache.manifest
|
However, the problem with the appcache API is it must be declared in the html tag at load time, it cannot be injected dynamically.
What this means is, if Service Workers are available and the appcache is always used, then we will end up having all the resources twice. In order to avoid this, we can dynamically create an iframe which loads an html that only references the manifest file (only when SW are not supported):
1
|
<html manifest=‘offline/appcache.manifest'></html>
|
Also, we need to add a condition to our registration code, in order to load the iframe:
1
2
3
4
5
6
7
8
9
10
11
12
|
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js').catch(function(err) {
console.log('Service Worker registration failed: ', err);
});
} else if ('applicationCache' in window) {
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = 'pwa/appcache/load-appcache.html';
document.body.appendChild(iframe);
}
</script>
|
Having that, we can check in Safari how it looks. There isn’t a Service Worker section, but an Application Cache section:
In addition, if you check that in Chrome, the application cache should be empty.