What is the PWA

PWA (Progressive Web Apps) is a project launched by Google in 2015. It aims to provide websites with similar native app experience through Web Apps.

advantages

1. Install without client and with a small amount of traffic 2. Add to the home screen and run in full screen 3. Offline function, faster response, timely update 4.PUSH capability 5. Data transfer must be HTTPS

disadvantages

2.PUSH is not mature enough and relies on Web PUSH Protocol. Chrome only supports Google proprietary GCM (Google Cloud Messaging) /FCM service for notification PUSH. Domestic Mipush also supports many apps. We hope that a unified push service can appear in China as soon as possible

Personal view

PWA is highly recommended because it is non-invasive, demotion-compatible, and has powerful offline capabilities for faster response.

Network Application List

The list of web applications is a JSON file, which mainly defines some configuration information such as startup url, custom icon, startup screen, theme color, and startup style. This is on page M of the App, and the browsers used by Domestic Android users do not support these definitions, so it will not be introduced in detail. The official document of The Web App Manifest, The webpack-manifest-plugin plugin can also be used to generate the Web App manifest Generator if you use Webpack

Service workers

Definition: Service Workers essentially acts as a proxy server between Web applications and browsers, and can also act as a proxy between browsers and networks when the network is available. They are designed, among other things, to enable the creation of an effective offline experience, intercept network requests and take appropriate action based on whether the network is available and whether updated resources reside on the server. They also allow access to push notifications and background synchronization apis.

Life cycle: Register → download → Install → Activate

Installing, installed, waiting, activating, and activated

Install prepares sw for use, such as creating a cache and placing an offline resource activate. At this point, the fetch can clean up the old cache and related things in order to update the fetch response to the request event. Processing the install, activate event triggers the waitUntil method

Note: 1. The Service workers are running on other threads and are completely asynchronous. Use Promise extensively

Cache

Methods add(), addAll(), delete(), keys(), match(), matchAll()

Basic usage

Create a separate app.js file, put it in the root directory, and reference it app.js in index.html


     
  1. if ('serviceWorker' in navigator) {

  2.  // register service worker

  3. The navigator. ServiceWorker. Register ('/service - worker. Js', {scope: '/'}) / / parameter 1: register provides the script URL parameter 2: navigation match

  4.  .then(function(registration) {

  5. // Registration succeeded

  6. The object holds state and state change events for the lifetime of the sw and some parent interface methods

  7. // The states are installing, installed, waiting, activating, and activated

  8.      if(registration.installing) {

  9.        console.log('Service worker installing');

  10.      } else if(registration.waiting) {

  11.        console.log('Service worker installed');

  12.      } else if(registration.active) {

  13.        console.log('Service worker active');

  14.      }

  15.  }).catch(function(error) {

  16. // Failed to register

  17.  });

  18. }

Copy the code

Create an executable file service-worker.js service-worker.js in the root directory


     
  1. // Cache static files

  2. self.addEventListener('install', function(event) {

  3.  event.waitUntil(

  4. // Cache the specified file

  5.    caches.open('v1').then(function(cache) {    

  6.      return cache.addAll([

  7.        '/',

  8.        '/index.html',

  9.        '/style.css',

  10.        '/app.js',

  11.        '/image-list.js',

  12.        '/star-wars-logo.jpg',

  13.      ]);

  14.    })

  15.  );

  16. });

  17. // Cache interface data

  18. self.addEventListener('fetch', function(event) {

  19.  event.respondWith(caches.match(event.request).then(function(response) {

  20. // The request was matched

  21. if (response ! == undefined) {

  22.      return response;

  23.    } else {

  24.      return fetch(event.request).then(function (response) {

  25. // Cache response data

  26.        let responseClone = response.clone();

  27.        caches.open('v1').then(function (cache) {

  28.          cache.put(event.request, responseClone);

  29.        });

  30.        return response;

  31.      }).catch(function () {

  32.        return caches.match('/gallery/myLittleVader.jpg');

  33.      });

  34.    }

  35.  }));

  36. });

  37. // Update the cache

  38. self.addEventListener('activate', function(event) {

  39.  event.waitUntil(

  40.    caches.keys().then(function(cacheNames) {

  41.      return Promise.all(

  42.        cacheNames.map(function(cacheName) {

  43. // If there is an update

  44. if (cacheName ! == 'v1') {

  45.            return caches.delete(cacheName);

  46.          }

  47.        })

  48.      );

  49.    })

  50.    .then(function(){

  51.      return self.clients.claim()

  52.    })

  53.  );

  54. });

Copy the code

Webpack project to upgrade PWA

The sw-Precach-webpack-plugin plugin will help you solve all your problems. Now let’s update the scaffolding of the small Web page packaging optimization article

1. Modify files:

  1. index.html


     
  1. <script>

  2.  if ('serviceWorker' in navigator) {

  3.      window.addEventListener('load', function() {

  4.          navigator.serviceWorker.register('./service-worker.js');

  5.      });

  6.  }

  7. </script>

Copy the code
  1. webpack.prod.config.js


     
  1. var SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin')

  2. // add to the plugins array

  3. new SWPrecacheWebpackPlugin({

  4.    cacheId: 'my-vue-app',

  5.    filename: 'service-worker.js',

  6.    minify: true,

  7. // See the official documentation for more configurations

  8. })

Copy the code

Service-worker.js is automatically generated and configured

2. Package ~ based on normal logic


     
  1. npm run build ZZSellerTip

Copy the code

3. Start a local static server

To facilitate debugging, Service workers can also run in http://localhost or http://127.0.0.1 local environments. Packaged files can be run through static servers generated by HTTP-server.

Turn off http-Server and you can see that it is still accessible

Note: If your static files are placed on a CDN, the server must have CORS enabled, as fetch requests are not supported across domains

Therefore, even if the project transformation is completed, the overall transformation cost is very low, so let’s do it together

— — — — — — — — —

Long press the QR code to follow the big Zhuan FE