For Web applications, it is natural that they cannot be used when they are offline. If we want to support offline, the purpose of service workers is to enable Web apps to compete with native apps in a real sense

A Service Worker is a script that the browser runs in the background independently of the web page, opening the door to functionality that does not require web pages or user interaction. They now include features like push notifications and background synchronization. The core functionality we discussed is intercepting and processing network requests, including programmatically managing responses in the cache,

Service Worker usage conditions

Normally, the browser window runs on the main JS thread, while the Service Worker runs on another thread, so there is no impact on the process of the browser page.

Since the Service Worker is completely asynchronous, synchronization apis such as XHR and localStrage cannot be used in it.

It can be used only when the following conditions are met:

  • Use HTTPS: To avoid possible use by middlemen for undesirable purposes, register the Service Worker only on pages served over HTTPS. However, in thehttp://localhostorhttp://127.0.0.1This local environment can also run
  • It is now supported by Chrome, FireFox and Opera

Service Worker life cycle

  1. Installing a service worker thread for the site: register the service worker thread in the JS of the page first. Registering the service worker thread will cause the browser to start the service worker installation step in the background

    / / register, This will tell the browser where the Service Worker JavaScript file is if ('serviceWorker' in navigator) {window.addeventListener ('load', Function () {//register where the file is If it is/eg/sw. Js, means that the service is the scope of the worker thread url/eg/start page navigator. ServiceWorker. Register ('/sw. Js). Then (= > {(registration) console.log('ServiceWorker registration successful with scope:', registration.scope) }, (err) => { console.log('ServiceWorker registration failed: ', err) }) }) }Copy the code
  2. During installation, some static resources are cached, and if all files have been cached successfully, the Service Worker is installed. If any files fail, the installation step will fail and it will try again next time

    var CACHE_NAME = 'my-site-cache-v1'; var urlsToCache = [ '/', '/styles/main.css', '/script/main.js' ] self.addEventListener('install', WaitUntil (// Open cache caches. Open (CACHE_NAME). Then ((cache) => {// Cache file return cache.addAll(urlsToCache) }) ); })Copy the code
  3. The activation

  4. The Service Worker exercises control over all pages in its scope and starts receiving fetch events.

self.addEventListener('fetch', (event) => {event.respondwith (caches. Match (event.request). Then ((response) => {if(response) {return response} // call Return fetch(event.request)})})Copy the code

The Service Worker update

When updating a Service Worker, follow these steps:

  1. When the JS file is updated, the browser will try to re-download the script file that defines the Service Worker in the background. If there is a byte difference with the current one, it will be regarded as the new Service Worker
  2. The new Service Worker starts and triggers the install event
  3. The new Service Worker enters the waiting state
  4. When the currently open page on the site is closed, the old Service Worker is terminated and the new Service Worker takes control
  5. When the new Service Worker gains control, its activate event is triggered
self.addEventListener('activate', (event) => { var cacheAllowlist = ['pages-cache-v1', 'blog-posts-chache-v1'] event.waitUntil( caches.keys().then((cacheNames) => { return Promise.all( cacheNames.map(item =>  { if (cacheAllowlist.indexOf(cacheName) === -1) { return caches.delete(cacheName) } }) ) }) ) })Copy the code

Relationship with PWA technology

PWA (Progressive Web Apps) is a Progressive Web application.

The core technologies of PWA include:

  • Web App Manifest – Add App ICONS to the home screen, define phone title bar colors, etc
  • Service Worker – Caching, offline development, geo-location processing, etc
  • App Shell – Display the main structure of the App first, then fill in the master data
  • Push Notification – Message Push

It can be seen that Service workers are part of PWA technology, but independent of PWA. In other words, although PWA technology is oriented to the mobile end, it does not affect the gradual use of Service Worker on the desktop end.

Application Service Worker

  • Background Data Synchronization
  • Respond to resource requests from other sources
  • Centrally receive computationally expensive data updates, such as geolocation and gyroscope information, so that multiple pages can use the same set of data
  • Performance enhancements, such as prefetching resources that a user might need

Good questions to share

Q1: What is PWA?

PWA is a progressive Web app, a concept Google introduced in 2015 that looks and feels like a native app. Pwa-enabled websites can provide offline work, push notifications, and hardware access to devices,

Q2: What are the advantages of PWA? – Smaller and faster, much smaller than native app, no waste of disk space, so very fast loading – responsive interface: support web pages automatically adapt to various screen sizes – no need to update: always load the latest version – cost-effective: Native App development needs to be developed separately for Android and iOS devices, which is expensive to develop – SEO advantage: The engine can find PWA maliciously and load very fast. – Offline features: Support for service Worker apis – Security: delivered over HTTPS connections and protects user data in every interaction – Push notifications: With push notification support, PWA makes it very easy to interact with users and provide a great user experience – Bypassing the App Store – zero installs

Q3: What are the disadvantages of PWA? – Low access to system functions – No review criteria: Lack of promotion benefits from the app store

Q4: How to make a Web application PWA?

The following principles should be observed:

  • Discoverable, content can be found through search engines
  • Installable and can be used on the device’s home screen
  • It is linkable and can be shared via the URL
  • Network agnostic and can work offline or with poor Internet connection
  • Progressive and works with older browsers
  • Re-participation is possible. Ability to send notifications whenever new content is available
  • security
  • But the response

Q5: What’s the difference between PWA and Hybrid?

A Hybrid is an application built using a combination of Web and native technologies that are distributed through app stores and approved by apple, Google, Microsoft, and others

Q6: What is App Shell?

The App Shell architecture is a way to build A PWA that can be reliably and instantaneously loaded onto the user’s screen.