The front-end technology is approaching like the desktop technology. One of the most important is serviceworkers, which makes it possible for the HTMLApp To Work offline. This article will describe this technology with a simple case code. Front-end technologies are approaching like desktop technologies. One of the most important aspects is service workers, which makes it possible for HTML apps to Work offline. This article will describe this technology with a simple case code. My tools:
1. the browser version is chrome 55.
2. The server system: Node 5.0
We need to prepare three files:
touch index.html b.html sw.js
The file index.html contains the following content:
《script》 if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js'); } 《script》
It registers a service worker with the file name sw. js and a JavaScript code file. So the key file is sw. js, whose content is:
const cacheName = 'v1::static'; self.addEventListener('install', e => { e.waitUntil( caches.open(cacheName).then(cache => { return cache.addAll([ '/', ]).then(() => self.skipWaiting()); }) ); }); self.addEventListener('fetch', event => { event.respondWith( caches.open(cacheName).then(cache => { return cache.match(event.request).then(res => { return res || fetch(event.request) }); }) ); });
As an event, install will be called when ServiceWorker is loaded for the first time. You can perform initialization here. A typical task is to load the files that are needed offline into the cache. Here we define "/", so any content will be cached.
The second event is fetch, which is called when a remote resource is accessed. Here we can make a match. If there is a match in the cache, the resources in the Qu cache will be returned. Otherwise, the system will remotely fetch the data.
The third B .html file is used to demonstrate the offline effect. The content is as follows:
serviceWorker B
You can install the http server and execute it in the current path:
npm i http-server http-server
Access:
http://localhost:8080/index.html
And
http://localhost:8080/b.html
Then, disable the http server and access it again.
http://localhost:8080/b.html
Actually accessible ~, This is the effect of offline implementation.
To view the running status of service workers, you can use the following url:
chrome://inspect/#service-workers
We can see that the details are as follows:
chrome://serviceworker-internals/
You can start and cancel registration operations here.
We can query its implementation, but it is not so optimistic:
http://caniuse.com/#feat=serviceworkers