Service staff tutorial

Service workers are a key technology that promotes the development of progressive web applications on the mobile web. They allow caching of resources and push notifications, which are the two main distinguishing features of native apps so far

Service staff profile

The service staff isProgressive web application, Because they allow caching resources and push notifications, which are the two main differentiating features of native apps so far.

The service staff isProgrammable AgentEffectively intercept and cache network requests between the web page and the networkEnables you to create an offline-first experience for your app.

This is a specialNetwork worker, AJavaScriptFiles associated with web pages running on the context of a worker thread (separated from the main thread) are non-blocking, so calculations can be made without sacrificing UI responsiveness.

Not on a separate threadDOMAccess, but no accessLocal storageAPI andXHRAPI, and can only useChannel Message API.

Service workers cooperate with other latest Web APIs:

they areOnly available on HTTPSProtocol pages (except for local requests), these pages do not require a secure connection for easier testing.

Background processing

Service workers operate independently of the applications they are associated with, and can receive messages when they are inactive.

For example, they can work:

  • When your mobile application isIn the background, Not active
  • When your mobile application isshut down, So even if it’s not running in the background
  • WhenBrowser is closedIf the application is running in the browser

The main scenarios that are very useful for service workers are:

  • They can be used asCache layerProcess network requests and cache content to be used when offline
  • allowPush notification

Service Workers only run when needed, and stop when they are not in use.

Offline support

Traditionally, the offline experience of web applications is very poor. Without the network, web mobile applications will generally not run, while native mobile applications can provide working versions or some form of exquisite messages.

This is not good news, but this is how the web page looks in Chrome without a network connection:

Offline support missing in service workers

The only possible benefit is that you can play free games by clicking on the dinosaurs, but you will soon get bored.

Dinosaur game chrome

Recently, HTML5 AppCache has promised to allow web applications to cache resources and work offline, but due to lack of flexibility and confusing behavior, it is clear that it is not up to the job and cannot deliver on the promise (andIt has been discontinued).

Service workers are the new standard for offline caching.

What kind of caching is possible?

Pre-cache assets during installation

Assets that can be reused throughout the application, such as images, CSS, and JavaScript files, can be installed when the application is opened for the first time.

This gives the so-calledApp Shell architecture.

Cache network requests

useExtract APIWe can edit the response from the server, determine if the server is unreachable, and provide the response from the cache.

Service staff life cycle

The service staff must go through 3 steps to fully work normally:

  • Register
  • installation
  • activation

Register

Registration will tell the browser the location of the server worker and start the installation in the background.

Sample code for registering the Service Worker placed in itworker.js:

if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/worker.js')
    .then((registration) => {
      console.log('Service Worker registration completed with scope: ',
        registration.scope)
    }, (err) => {
      console.log('Service Worker registration failed', err)
    })
  })
} else {
  console.log('Service Workers not supported')
}

Even if this code is called multiple times, the browser will only perform registration when the service worker is new, not previously registered or updated.

range

Thisregister()The call also accepts a scope parameter, which is a path that determines which part of the application the service worker can control.

It defaults to all files and subfolders contained in the folder containing the service worker files, so if you put it in the root folder, it can control the entire application. In the subfolder, it will only control the pages accessible under that route.

The following example specifies/notifications/Folder scope.

navigator.serviceWorker.register('/worker.js', {
  scope: '/notifications/'
})

This/Very important: In this case, the page/notificationsIf the range is

{
  scope: '/notifications'
}

It will work.

Note: Service workers cannot upgrade from the folder "self": if you put their files below/notifications, It can't control/Path or any other path not below/notifications.

installation

If the browser determines that the service worker is out of date or has never been registered before, it will proceed with the installation.

self.addEventListener('install', (event) => {
  //...
});

This is a good event for preparing service workers to use,Initialize the cache, withCache application shellAnd static asset usageCache API.

activation

Once the service worker is successfully registered and installed, the activation phase is the third step.

At this point, the service worker will be able to handle the new page load.

It cannot interact with loaded pages, which means that the service worker is only useful when the user interacts with the application for the second time or reloads one of the opened pages.

self.addEventListener('activate', (event) => {
  //...
});

A good use case for this event is to clear the old cache and content associated with the old version but not used in the new version of the service worker.

Update service staff

To update the Service Worker, you only need to change one byte in it, and when the registration code is run, it will update it.

After the Service Worker is updated, it will not become available until all the pages to which the old Service Worker is attached are closed.

This ensures that there is no damage on the application/page that is already running.

Refreshing the page is not enough, because the old work program is still running and has not been deleted.

Get event

A kindFetch eventTriggered when a resource is requested on the network.

This allows us toView in cacheBefore making a network request.

For example, the following code snippet usesCache APICheck whether the request URL has been stored in the cached response, and if this is the case, return the cached response. Otherwise, it will execute the get request and return it.

self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request)
      .then((response) => {
        if (response) { //entry found in cache
          return response
        }
        return fetch(event.request)
      }
    )
  )
})

Background sync

Background synchronization allows the outgoing connection to be postponed until the user has a valid network connection.

This is the key to ensuring that users can use the application offline and perform operations on it, and queue server-side updates when the connection is open, rather than showing an endless spinning wheel trying to get a signal.

navigator.serviceWorker.ready.then((swRegistration) => {
  return swRegistration.sync.register('event1')
});

This code listens to the event in the Service Worker:

self.addEventListener('sync', (event) => {
  if (event.tag == 'event1') {
    event.waitUntil(doSomething())
  }
})

doSomething()Return the promise. If it fails, another synchronization event will be scheduled to automatically retry until it succeeds.

This also allows the application to update data from the server as soon as a connection is available.

Push event

Service workers can enable Web applications to provide users with native "push notifications" in the following ways:

Push and notification are actually two different concepts and technologies, but the combination can provide what we knowPush notification. Push provides a mechanism that allows the server to send information to service personnel, and notification is a way for service personnel to display information to users.

Since Service Workers can run even when the application is not running, they can listen to upcoming push events and provide user notifications or update the status of the application.

Push events are initiated by the backend through the browser push service, for example byFirebase.

This is an example of how a service worker listens to incoming push events:

self.addEventListener('push', (event) => {
  console.log('Received a push event', event)

const options = { title: ‘I got a message for you!’, body: ‘Here is the body of the message’, icon: ‘/img/icon-192x192.png’, tag: ‘tag-for-this-notification’, }

event.waitUntil( self.registration.showNotification(title, options) ) })

Notes on the console log

If you have any console log statements (console.logAnd friends) in the service worker, please make sure you turn onPreserve logProvided functionsChrome DevTools, Or equivalent.

Otherwise, since the service worker will perform operations before loading the page and clear the console before loading the page, no logs will be displayed in the console.

Download mine for freeJavaScript beginner's manual


More browser tutorials: