Progressive Web Apps aim to achieve user experience similar to native apps through various Web technologies. Looking at the gap between existing Web applications and native applications, such as offline cache, immersive experience, etc., we can use the Web technology to bridge these gaps and finally achieve user experience similar to native applications.

  • Strict reliance on HTTPS ensures certain security

features

  • Safe and reliable

The Service Work technology is used to realize instant download. After users open the application, the loading of page resources is no longer completely dependent on the network. Service Work is used to cache offline packages locally to ensure instant and reliable experience for users.

  • Access to faster

The first screen can be deployed on the server, saving the time of web page requests, faster loading speed, smoother dynamic effect and faster page response.

  • Responsive interface

Supports various types of terminals and screens.

  • Immersive experience

Pwa-enabled browsers and mobile apps can add Web apps directly to the user’s home screen, eliminating the need to download and install them from the app store. Provide an immersive, full-screen experience once the app is opened from the home screen.

function

The Web App Manifest can be configured through the manifest.json file so that it can be added directly to the desktop of the phone.

Offline loading and caching (Service Worker+Cache API) A series of Web technologies, such as Service Worker+ HTTPS +Cache API + indexedDB, can be used to implement offline loading and caching.

Push&Notification Enables real-time message push and notification

Background Sync Synchronizes Background data in a timely manner

Introduction of PWA core technology

1.service Worker

A service worker thread, similar to a Web worker, is a separate process from the main JS process.

A middleman role between server and browser. If a service worker is registered in a website, it can intercept all requests of the current website and make judgment. If it needs to send a request to the server, it can directly return the request to the cache instead of sending it to the server. This greatly improves the browser experience.

  • Resident memory run
  • Proxy network request
  • Relying on the HTTPS

2. promise

A number of promise apis exist in service workers

Fetch Network request

catch API

A resource caching system that allows web pages to run even when there is no network to use cached resources

  • Cache resources (CSS /script/image)
  • Rely on the Service Worker agent for network requests
  • The page can be run offline

Notification API

Send a background push message

Being pushed

  • Depend on User Authorization
  • Suitable for pushing in service workers

PWA core technology learning

service-worker

Registered serviceWorker

index.js

  <script>
      / / register serviceWorker
      navigator.serviceWorker
        .register("./sw.js", {
          scope: "/".// The relative path that the script can control. Default is the path where the script itself is located
        })
        .then(
          (registration) = > {
            // Return registration on success
            console.log(registration);
          },
          (err) = > {
            // Return to err on failure
            console.error(err); }); </script>Copy the code

use

Write the installation and interception logic in the specified serviceworker.js.

There are several points in sw.js
  1. Dom inaccessible
  2. Window, location, etc cannot be accessed
  3. Service worker programming is about dealing with the life cycle of the service worker
  4. Self represents the current serverWorker
  5. It is designed to be fully asynchronous, and synchronization apis such as XHR and localStorage are not available in service workers

The following code is in sw.js

1. Install the worker
  • Listen for the install event, which is typically used to set the browser’s offline cache logic
  • The install method is triggered when a new Serviceworker script is installed,
  • Note that if sw.js is even slightly different, the browser will assume it is a new service worker, and the new version will be downloaded and installed, not immediately, with the same effect as the previous version
  • Install and Activate will be triggered the first time the page is installed, but will not be triggered if the page is refreshed again because it is already installed. Unless the script changes.
self.addEventListener("install".(event) = > {
  WaitUntill (promise) is complete only after the incoming promise is complete, delaying the activation of the next activate. WaitUntil usually combines some specific behavior
  / / such as
  // self.skipWaiting() forces the old Serviceworker to stop and the new serviceworker to start
  // To force the old serviceWorker to stop using the new version after installing the new version,
  // Because the new version does not take effect immediately
  event.waitUntil(self.skipWaiting());
});
Copy the code
2. Activate the serviceWorker

This step is to let the serviceWorker complete the installation and make all pages under the Control of the serviceWorker. Or clear some related resources left by the previous worker, such as useless cache

self.addEventListener("activate".(event) = > {
  console.log("activate", event);
  // Make all pages under the control of serviceWorker
  event.waitUntil(slef.client.claim());

  //
});
Copy the code

After the above two steps, serviceWorker has full control over all pages.

3. The fetch method

In fetch we can intercept all requests to the whole site. Here we can compare it to the cache and decide whether to send the request or return the cache.

self.addEventListener("fetch".(event) = > {
  console.log("fetch", event);
});

Copy the code

cache API

When you go offline, you can see that the resource cache API doesn’t have to be used in serviceWorker to write to the cache in a page

const Cache_Name = "Cache_v1";
self.addEventListener("install".(event) = > {
  event.waitUntil(
    //
    /* Create a cache version called Cache_V1 */
    caches.open("v1").then(function (cache) {
      /* Specifies the content to cache. The address is the access path relative to the domain name */
      cache.addAll(["/"."./index.css"]); })); }); self.addEventListener("activate".(event) = > {
  // The cache may change if a new version of serviceWorker is created
  // Activate can clear unnecessary caches
  event.waitUntil(
    caches.keys().then((cacheNames) = > {
      return Promise.all(cacheNames).then((cacheName) = > {
        if(cacheName ! == Cache_Name) {// Be careful to return because caches. Delete also returns a promise
          returncaches.delete(cacheName); }}); })); });// Fetch some requests
self.addEventListener("fetch".(event) = > {
  event.respondWith(
    /* Return */ if the cache matches the requested resource
    caches.open(Cache_Name).then((cache) = > {
      return cache.match(event.request).then((response) = > {
        // Response has a hit cache and is returned directly to the cache
        if (response) {
          return response;
        }
        // If the response does not exist, send the request to get the data and put it into the cache
        return fetch(event.request).then((response) = > {
          // Response is a stream that needs to be cloned
          cache.push(event.request, response.clone());
          returnresponse; }); }); })); });Copy the code

ServiceWorker learning guide: developer.mozilla.org/zh-CN/docs/…

notification API

Notification API – For the interface used to configure and display desktop notifications to users. It is forbidden in sw script below need to set notification in the page

let notification = new Notification(title, options)
Copy the code
  • title

  • The notification title must be displayed

  • The options of the optional

  • An object that is allowed to set notifications. It contains the following attributes:

    • dir: direction of text; Its value could beAuto.LTR (left to right), or rtl(From right to left)
    • lang: Specifies the language to use in the notification.
    • body: Additional string to display in the notification
    • tag: Gives the notification an ID so that it can be refreshed, replaced, or removed if necessary.
    • icon: the URL of an image that will be used to display the notification icon.

Some properties of notification

1. Notification.permissionread-only

Gets the authorization status of the notification

  • deniedThe user refused to display the notification.
  • grantedThe user allowed the notification to be displayed.
  • default(Because the user’s choice is not known, the browser behaves the same as when denied).

Some methods of notification

1. Notification.requestPermission()

Apply for permission to display notifications to the user on the current page.

2. Notification.close()

Close to inform

How to use it in sw script?

  1. In the page authorization to allow notification. RequestPermission ()
  2. In sw script file by self. Registration. ShowNotification () is used