I. Traditional Web applications

Web apps are not as popular in the mobile era as they are on desktop devices. Here’s a chart to compare the differences with native apps.



The reasons are as follows:

  • Mobile device network limitations – non negligible load times
  • Web applications rely on the browser as an entry point
  • The gap between experience and native

If the above points can be solved, how much improvement for Web app can be imagined.

What is PWA

PWA stands for Progressive Web Apps(Progressive Web Applications), which aim to provide a better user experience using existing Web technologies. The basic requirements

  • Reliable loads and displays instantaneously even in an unstable network environment
  • Fast Response (Fast) Fast response and smooth animation in response to user operations
  • Engaging is like a native app on a device, with an immersive user experience that users can add to the desktop

The PWA itself emphasizes gradual progress and does not require all requirements on safety, performance and experience to be met at one time. Developers can check the existing characteristics through the PWA Checklist.

In addition to the above benchmark requirements, the following features should also be included:

  • Progressive – Works with all browsers because it was developed with progressive enhancement in mind
  • Connection independence – Can be accessed offline or on a poor network with the help of the Service Worker
  • Similar application – developed on the basis of App Shell model, it should have the interaction and navigation of Native App to give users the experience of Native App
  • Continuous updates – always up to date, no version or update issues
  • Security – Provides services over the HTTPS protocol, preventing snooping and ensuring that content is not tampered with
  • Indexable – Application manifest files and Service workers can be indexed by search engines to recognize them as “applications”
  • Engagement – Users can return via push offline notifications, etc
  • Installable – Users can add common WebApps to their desktop without having to download them from the app store
  • Linkable – Share content through links without downloading and installing

Looks a little giddy, is this another flying wheel? To reiterate,PWA is not a new technology behind it, but rather a collection of current web technologies. Each uses its own functionality to fulfill incremental overall requirements. Here is a look at the related technologies along with the previous questions

Iii. Technical composition

It consists of the following technologies:

  • App Manifest
  • Service Worker
  • Notifications API
  • Push API

Among them, Service Worker is the key to PWA technology, which can make app meet the above three benchmarks. Other technologies are icing on the cake, making apps more powerful.

3.1 Service Worker Background

Offline Cache background

There have been a lot of efforts, both before and after, to reduce the response time of the web experience, without describing the various technical measures here. The other direction is caching, reducing unnecessary interaction with the server, but the browser cache is not strong for offline situations, so the need for offline caching arises.

The history of offline caching

The development of offline cache for Web applications is not a cluster, but a gradual process of improvement. The initial solution was AppCache. However, this proved to be a failure with so many flaws that it was scrapped. You can check Application Cache is a douchebag, but the direction is still correct, so keep exploring.

workers

Persistence aside for a moment, let’s talk about another issue: the reality of single-threaded javaScript in the browser is becoming increasingly inadequate for the needs of the modern Web, such as time-consuming calculations, and user interactions are clearly affected. To free these time-consuming operations from the main thread, the EARLY W3C added a Web Worker API that can be executed independently of and interact with the main thread. However, Web workers are temporary and rely on creating pages, which can’t meet our needs for persistence. For this purpose, the following is relatively easy to solve, to build a lasting existence on the line. On the basis of Web workers, W3C added service workers to meet our persistence needs. Its life cycle is independent of the page. When the associated page is not closed, it can also exit, and when there is no associated page, it can also start the function

Although the Service Worker satisfies offline caching, its functions are not limited to this. Can provide

  • Rich offline experience,
  • Periodic background synchronization,
  • Push notifications,
  • Intercept and process network requests,
  • Managing resource caching is also the purpose of PWA, so the Service Worker is a key technology for PWA.

The premise condition

For the sake of security and its implementation principle, Service Worker has certain preconditions when it is used.

  • Because Service workers require HTTPS environment, of course, browsers generally allow debugging of Service workers when host is localhost or 127.0.0.1
  • The caching mechanism of Service workers relies on the Cache API (omitted)
  • Rely on the HTML5 Fetch API (skipped)
  • It is not supported by all browsers. The support is as follows:

3.2 the Cache

Cache is an API derived from Service Worker, which implements caching of resource requests with Service Worker. Instead of caching strings directly, cache caches requests for resources (CSS, JS, HTML, and so on). Cache is also in the form of key-value. Generally, a key is a request and a value is a response

  • Caches. Open (cacheName) Opens a cache
  • Caches are global objects that return a Promise with a cache return value
  • Cache.keys () iterates through all the keys in the cache to get a set of values
  • Cache. Match (Request | url) in the cache match the incoming Request, return Promise;
  • Cache. matchAll differs from match only in the first argument, requiring an array of request and of course returning an array of response
  • Cache. The add (Request | url) is not a simple add, because of the incoming Request or url, in the cache. The add internal will automatically go to call the fetch back the Request of the Request as a result, and then save the response in the cache;
  • Cache. addAll is a request for all files that need to be cached
  • Cache. put(Request, Response) This is equivalent to the second step of cache.add
  • Cache. Delete (Request | url) to delete the cache

3.3 Registering a Service Worker

Registration, which declares the location of the SW file, should obviously be introduced in the main JS. As follows:

/ / based on a promise
function registerServiceWorker(){
    // Register the service worker
    return navigator.serviceWorker.register('./sw1.js').then(registration= > {
        console.log('Registration successful');
        / / return
        return registration;
    })
    .catch(err= > {
        console.error('Registration failed', err);
    });
}
window.onload = function () {
    // Supported or not
    if(! ('serviceWorker' in navigator)) {
        return;
    }
    registerServiceWorker()
}
Copy the code

3.4 Life Cycle

Service workers have a life cycle independent of web pages. To install a Serice worker on a website, you need to register and the browser will install the service worker in the background. Then you go to the different stages below. Once activated, the Service worker takes control of all pages and brings them into its scope, but does not control the page the first time it registers the service worker on the page until it is loaded again. After the service worker takes effect, it will be in one of two states:

  • The service worker terminates to save memory,
  • After the page initiates a network request, it handles the request fetch and message events.

As can be seen from the figure above, it is divided into the following stages:

  • Installing occurs after the Service Worker is registered, indicating that the installation begins, and the install event callback is triggered to specify some static resources for offline caching
  • The Installed Service Worker has completed the installation and is waiting for other Service Worker threads to be shut down.
  • Activating a client in this state that is not controlled by another Service Worker allows the current Worker to complete the installation
  • Activated handles the activate event callback in this state (providing an opportunity to update the cache policy). It can also handle functional events fetch, sync, and push.
  • Redundant is replaced, that is, Redundant is destroyed

The purpose of understanding the declaration cycle is to listen for events at different times to perform operations. There are two main events for the PWA.

  • Install event callback:

Event.waituntil () : Pass a Promise until the Promise is in the resolve state. Self.skipwaiting () : self is the global variable of the current context. Executing this method forces the Service Worker currently in waiting to enter the activate state.

  • Activate the callback:

Event.waituntil () : Pass a Promise until the Promise is in the resolve state. Self.clients.claim () : Execute this method in the Activate event callback to gain control of the page so that the version update cache is used when the page is opened later. The old Service Worker script no longer controls the page and will be stopped later.

const CURCACHE = 'CURCACHE_test_1'
const RUNTIME = 'runtime';
const CURCACHE_URLS = [
    '/'.'/asset/sw.jpg'.'index.js'
]
self.addEventListener('install',e=>{
    e.waitUntil(
      // Store the resources corresponding to the cache path
        caches.open(CURCACHE).then(cache= >{
            cache.addAll(CURCACHE_URLS)
        }).then(
            self.skipWaiting()
        )
    )
})
 
 
   
  // Proxy requests, using caching, before the request is sent
  self.addEventListener('fetch', e => {
    e.respondWith(
      // Whether the cache matches
      caches.match(e.request).then(function(response) {
        if(response ! =null) {
          // Cache hit returns cache, end request
          return response
        }
        // No cache hit, normal request
        return fetch(e.request.url)
      })
    )
  });
Copy the code

Update service worker Service worker update steps are as follows:

  • Update the service worker’s file web page is compared by the server to keep it up to date
  • The new service worker starts install
  • The current page is still in effect for the old service worker, and the new service worker will enter the state of “waiting”.
  • After the page closes, the old service worker is killed and the new Servicer worker takes over the page
  • A new service worker triggers an activate event when it takes effect.
const CURCACHE = 'precache_test_1'
Precache_test_2 = CURCACHE; // Precache_test_2 = CURCACHE
self.addEventListener('activate', e => {
  e.waitUntil(
      // Iterate over the current cache keys
      caches.keys().then(cacheNames= >{
        return Promise.all(
          cacheNames.map(function(cacheName) {
            // Is equal to the current key
            if(cacheName ! == CURCACHE) {return caches.delete(cacheName);
            }
          })
    )}).then((a)= > self.clients.claim())
 )
}) 
Copy the code

Such a simple service worker offline cache is complete. The console can see that the source is the service worker


4. Add to the home screen

Allowing sites to be added to the home screen is an important feature provided by PWA. This eliminates the need to rely on the browser as the platform, which is in line with mobile user habits.

manifest.json

The manifest.json file is required to configure the application icon, name and other basic information as follows:

{
    // The text that appears when prompted to install the application
    "name": "PQJ-PWA".// Text added to the home screen
    "short_name":"PQJ"."description": "The test demo".// Start the address after adding it
    "start_url": "/index.html".// Icon information
    "icons": {
      "128": "/asset/sw.jpg"
    },
    "developer": {
      "name": "pqj"."url": ""
    },
    "display": "standalone"."background_color": "#287fc5"."theme_color": "#fff"."permissions": {
        "desktop-notification": {
          "description": "Needed for creating system notifications."}}}Copy the code

It is then introduced in HTML as follows

<link rel="manifest" href="/mainfest.json" />
Copy the code

Once this is done, Mobile Android uses Chrome (in beta), which will prompt you to allow it to be installed on the home screen for the first time, in the form of an app icon. The image and text are determined by the configuration.

V. News notification

Message notification is also performed using the notification function of the service worker, which allows the server to notify the user of certain behaviors rather than the user’s active request. Normal notification logic requires the server to participate in the implementation; this demonstration only implements functionality.

  • Apply for notification permission first
  • Registration service worker
  • Processing logic, sending notifications
function getPermission(){
    return new Promise((resolve, reject) = > {
        // Obtain permission
        const permissionPromise = Notification.requestPermission(result= > {
            resolve(result);
        });
    }).then(result= > {
            // Determine the condition
            if (result === 'granted') {
                execute();
            }
            else {
                console.log('no permission'); }}); }Copy the code

Send a notification

function execute() {
    // Execute after permission
    registerServiceWorker().then(registration= > {
        / / notice
        registration.showNotification('Hello World! ');
    });
}  
Copy the code

conclusion

Reference documentation

Lavas.baidu.com/doc developer.mozilla.org/zh-CN/Apps/…

Although PWA currently faces many limitations, it can also be seen that Web organizations are making efforts to better improve the direction of Web applications. As always mentioned, the future is predictable. At present, Baidu in China is more mature in this regard, and Sina Weibo has a BETA version of PWA.