PWA web pages can be used offline by caching web resources through Service workers. Currently, Android WebView already supports Service workers. However, the problem with the Service Worker technology is that it needs to be run once to get the caching effect. How to make PWA web page launch for the first time, also have cache effect? One solution I came up with is to execute the Service Worker on the server in advance, obtain the cached resources, type them into offline packages and deliver them to the client. Node.js is the first thing that comes to mind when implementing the Service Worker on the server. Service workers are js based and node is the best way to implement them. Among them, emulating the importScript interface is a difficulty. The Service Worker calls the external module with importScript. The solution is to use the VM of Node as the container of the Service Worker. Execute the Service Worker through the runInContext interface, or inject the importScript module.

// Initialize the VM contextglobal.swContext = vm.createContext(swGlobalScope); .// Execute the Service Worker, or inject the module 'importScript'
 const script = new vm.Script(scriptContent);
 script.runInContext(global.swContext);
Copy the code

service-worker-node

Service-worker-node has been developed and published to NPM. Service-worker-node Provides a service worker execution environment for Nodes. You can pre-fetch the cache list on the server side, or do some automated testing.

npm install service-worker-node
Copy the code

For specific API usage, see service-worker-node

The source code

service-worker-node