Working Offline
You can create the plugin to work offline using two possible approaches, or a combination of them.
The approaches are:
- Using Service Worker API (See https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API): This is the preferred way to implement the offline functionality for the plugin. It is supported by most browsers, except Internet Explorer 11.
- Combination approach: Use the Service Worker API for modern browsers and Application Cache
API as a fallback mechanism for Internet Explorer 11. The basic principles of this solution
are:
- Create the mainfest.appcache file and link it with the index.html by adding the "manifest"
attribute to main html tag:
The manifest.appcache must contain the list of cached files in the "CACHE" section.<html manifest="manifest.appcache">Tip: Do not add "index.html" to the CACHE section to enable possible future updates of the plugin's resources. - Create the Service Worker javascript file (for example, service-worker.js). This file must implement the network behavior of your plugin using ServiceWorker API. It may load "manifest.appcache" file on the "install" event, parse the Application Cache file and add all the files from the "CACHE" section to browser's cache using the CacheStorage interface. After that you can implement any network behavior strategies to handle the "fetch" event: "network first then cache", "cache first then network", or "network only".
- Register your Service Worker file at the JS part of your plugin, before sending the
"ready" post message, for
example:
if (navigator.serviceWorker) { navigator.serviceWorker.register('service-worker.js').then(function (registration) { this.startApplication(); }.bind(this), function (error) { console.error('Service Worker registration failed: ', error); startApplication(); }.bind(this)); } else { startApplication(); }
- Create the mainfest.appcache file and link it with the index.html by adding the "manifest"
attribute to main html tag:
In this code example, the `startApplication()` function sends the "ready" post message. It's important to postpone sending the "ready" message until the "install" event is handled properly and all files from the CACHE section of manifest.appcache are loaded to the browser's cache.