What is the PWA

PWA (Progressive Web Apps) uses modern Web apis and traditional Progressive enhancement strategies to create cross-platform Web applications. These apps are ubiquitous and feature-rich, giving them the same user experience advantages as native apps. (From MDN)

In general, web pages on mobile can present a similar native user experience.

Chromium started working on service Workers in March 2014 and Chrome for Android release 40 in November 2014. At Google Developer Conference 2016, pWA-related technologies were promoted and the concept of PWA became popular. Since then, PWA has been a staple of major technology conferences. IOS Safari’s Safari Technology Preview Release 49, released in February ’18, officially announced support for Service Workers, clearing the biggest obstacle to the development of PWA.

18 was a year of rapid development for PWA. In 2019, the enthusiasm seems to have waned. Some people even ask whether PWA(Progressive Web App) will cool down in 2019. In general, the development of the technology is largely dependent on Google’s promotion.

advantage

PWA is Web-based, so h5 can do everything it can

  • Easy to install

Through the manifest configuration, users can be actively prompted or passively installed on the desktop by users. Or use a third-party service (such as Microsoft’s Pwabuilder) to wrap it as a native app

  • Independent of the network

Use ServiceWorker to load page resources early and run them offline

  • Can link

Apps can be accessed via generated desktop ICONS, a native experience (no browser address bar)

  • Can push

ServiceWorker has certain background running permissions and can accept pushes from websites just like a native app

  • Automatic updates

The ServiceWorker automatically updates the PWA in a controlled way in the background

  • progressive

None of the above extensions are optional, but you can gradually support them on your existing Web app as you see fit, allowing seamless compatibility and migration between older browsers and existing sites

  • Security:

Network or localhost that requires HTTPS (for local debugging)

compatibility

service workers

Comparison between PWA and other apps such as small program

PWA Small program HTML5 native(iOS/Android) Electron
installation Click to play and optionally add to the desktop for full screen running Point-to-use, alipay/wechat and other terminals run Click “out of the box” to add shortcuts to your desktop From appstore installation Download the installation package from the official website
Take up the space lightweight Light weight with size limitation lightweight It can be big or small. It’s not limited Large, built-in Chromium Runtime
performance In the In the In the high In the
cross-platform IOS /Android/ Desktop (newer browser required) Rely on Alipay/wechat Through the browser Only the target platform is supported Across desktops, mobile devices are not supported
Independent operation Yes (browser dependent) no no is Yes (built-in browser)
Interact with native Few other capabilities (via schema, etc.) depend on the browser implementation Easy (via interfaces such as JsBridge provided by the container) Few other capabilities (via schema, etc.) depend on the browser implementation Natural support Yes (via the ELECTRON API)
The distribution Depending on the site, CDN can be used Alipay/wechat provides CDN Depending on the site, CDN can be used appstore Manually install or MacAppstore, etc
offline is is no is is
Version control Through ServiceWorker Via Alipay/wechat There is no Appstore push Manual upgrade
Push message ServiceWorker Borrow alipay/wechat capabilities ServiceWorker Native Push (FCM/APNS) Self-maintenance background push
Hot update ServiceWorker Borrow alipay/wechat capabilities Every refresh is new Hard, need to hack Plugins available
security Mandatory HTTPS Guaranteed by the platform Don’t force HTTPS

emphasis

service workers

At the heart of PWA, like cookies, is the concept of a Path Path, which is recommended to be registered in a top-level directory to manage all pagesCopy the code

In the case of the web page has been closed can also run, used to achieve the page cache and offline, background notice and so on

The characteristics of

  • After the page is registered and installed successfully, it runs in the background of the browser and is not affected by page refresh. It can monitor and block HTTP requests of all pages within the scope.
  • Websites must use HTTPS. Except when debugging with the local development environment (such as using localhost for domain names)
  • Running in the browser background, you can control all page requests under the open scope
  • Separate scope, separate runtime environment and execution thread
  • Page DOM cannot be manipulated. But it can be handled through the event mechanism
  • Event-driven service threads

The global variable

  • Self: represents the Service Worker scope and is also a global variable
  • Caches: cache
  • skipWaiting: Waiting: forces a script currently in waiting to enter the activate state (refresh the page only by invoking registration, re-register depends on whether the current sw already exists, re-register when the file name or content changes, new SW will be installed first, then waiting.) When the browser restarts, the old SW will be replaced, and the new SW will enter the active state. If skipWaiting is reached through install, the process of waiting for the browser to restart will be skipped.
  • Clients: represents the page taken over by the Service Worker

The life cycle

The register (registration)
if ('serviceWorker' in navigator) { window.onload = () => { navigator.serviceWorker.register('sw.js') Then ((registration) => {console.log('serviceWorker registration successful, it is: ', registration); }) .catch(function (err) { console.log('serviceWorker registration failed: ', err) }); }}Copy the code
Install
Cache.match(request, options) returns a Promise object. Resolve is the first cached request that matches the cache object. Cache.matchall (request, options) returns a Promise object. The result of resolve is an array of all requests matching the Cache object. Cache.addall (requests) receives an array of urls, retrieves and adds the returned Response object to the given Cache object. Cache.delete(request, options) Searches for Cache entries whose key is request. If found, the Cache entry is deleted and a Promise object that resolves to true is returned. If not found, return a Promise object that resolves to false. Cache.keys(request, options) returns a Promise object, and resolve returns an array of Cache keys.Copy the code
const CACHE_VERSION = 'pwa-cache-key'; const CACHE_LIST = [ "./css/index.css", "./image/logo.png" ]; Self. addEventListener('install', e => {console.log('install',); Caches. Open (CACHE_VERSION) // Add files to cache. Then (cache => Cache.addall (CACHE_LIST)).then(() => {// The method self.skipWaiting() is called so that the new Service Worker script can be activated immediately while the page is being updated. self.skipWaiting(); })); });Copy the code
Self. addEventListener('fetch', function (e) {console.log('fetch: Match (e.equest). Then (function (cache) {// If there is a cache, use the cache. There have been new send request for return cache | | the fetch (" e.r equest)}). The catch (function (err) {the console. The log (err) / / cache error also directly from the new request for the return fetch(e.request) }) ) })Copy the code
Activate (activate)
// Listen to the activate event, Self. addEventListener('activate', function (e) {console.log('Service Worker status: Activate ') var cachePromise = caches. Keys (). Then (function (keys) {// Scope (key) Promise.all(key. map(function (key) {// If (key! == cacheName) {return caches. Delete (key)}}))}) e.waitUntil(cachePromise) // Ensure that the fetch triggers a return the first time it loads self.clients.claim() })Copy the code
Redundant (waste)

Browser cache mode

From Memory Cache memory that exists only when the browser is running, such as Base64 image data and static resources, but cannot be controlled

From Disk Cache A hard disk that is cached for a long time, such as static resources, and cannot be controlled

From ServiceWorker SW agent, fully controllable

The sample

Mainifest. Json configuration file

This configuration file needs to be imported into the entry page

{"name": "pwa demo", // Mandatory, plugin name" short_name": "demo pwa ", // optional in APP Launcher and the new TAB page display, if not set, use name" description": "The app that helps you understand PWA", // App description "display": "standalone", // App display mode. Fullscreen: displays in fullscreen. It tries to fill up all display areas. Standalone: Browser-specific UI (e.g. navigation bar, toolbar, etc.) will be hidden so it looks more like a Native App. Minimal-ui: Similar to the standalone display, the browser-specific UI is minimized to a single button, which varies slightly from browser to browser. Browser: In general, the browser will open the same as normal use of the browser (PS: Some browsers on systems that do not support fullscreen will display the standalone effect, those that do not support the standalone property will display the mole-UI effect, and so on). "Start_url ": "/", // The app startup URL "theme_color": "#8888ff", // the desktop icon background color" background_color": "#aaaaff", // the predefined background color for the Web application. A smooth transition is created between starting the Web application and loading the content of the application. "ICONS ": [// desktop ICONS {" SRC ": "image/logo.png", "sizes": "256x256", // Multiple image sizes separated by Spaces "type": "Image/PNG" // help userAgent quickly exclude unsupported types}]}Copy the code

Official configuration description address

Use cases

Google, as a promoter, uses PWA more frequently, such as Youtube Music, Google Photos, Android Messages, Facebook Mobile, and Twitter

What Web Can Do Today: PWA compatibility check site to see which PWA features your browser supports

AppScope: PWA App Store itself is a PWA, and all apps included in it are ALSO PWA

React provides PWA documentation

The official Create React App PWA document

Third-party React PWA documents

Community open source React PWA framework