Service Workers essentially act as proxy servers between the Web application, the browser, and the network (when available). This API is designed to create an effective offline experience by intercepting network requests and taking appropriate actions to update resources from the server based on whether the network is available. It also provides entry for push notifications and access to background synchronization APIs.

The concept and usage of Service worker

The Service worker is an event-driven worker registered at the specified source and path. It uses JavaScript to control associated pages or websites, intercept and modify access and resource requests, and cache resources in a fine-grained way. You have complete control over how your application behaves in certain situations (most commonly when the network is not available).

The Service worker runs in the worker context, so it cannot access the DOM. It runs in a different thread than the main JavaScript thread driving the application, so it does not cause a block. It is designed to be completely asynchronous, and synchronous APIs (such as XHR and localStorage) cannot be used in the service worker.

For security reasons, Service Workers can only be hosted by HTTPS, since the ability to modify network requests would be very dangerous to expose to a man-in-the-middle attack. In Firefox privacy mode, Service Worke is not available.

Note: Service Workers have more granular control over everything and support terminating operations when something goes wrong

Note: Service Workers make heavy use of Promises because they typically wait for a response and continue, returning either a successful or a failed operation based on the response. Promise fits well in this scenario.

registered

Using ServiceWorkerContainer. The register () method for the first time registration service worker. If the registration is successful, the service worker is downloaded to the client and an attempt is made to install or activate (see below), which will be applied to a user-accessible URL for the entire domain, or a specific subset of it.

Download, install, and activate

At this point, your service worker will observe the following lifecycle:

  1. download
  2. The installation
  3. The activation

The first time a user visits a site or page controlled by the service worker, the service worker is immediately downloaded.

After that, updates will be triggered in the following situations:

  • A navigation to the scoped page
  • An event was triggered on the service worker and has not been downloaded for the past 24 hours

Whether it is different from an existing service worker (byte comparison) or the first time a service worker is encountered on a page or website, the installation will try to proceed if the downloaded file is new.

If this is the first time the service worker has been enabled, the page will first attempt the installation, and it will be activated when the installation is successful.

If the existing service worker is enabled, the new version will be installed in the background, but will not be activated. This sequence is called worker in waiting. A new service worker is not activated until all the loaded pages are no longer using the old service worker. The new service worker is activated as soon as the page no longer relies on the old service worker.

You can listen to InstallEvent, and the standard behavior when an event is triggered is to prepare the service worker for use, such as using the built-in Storage API to create a cache, and to place resources needed when the application is offline.

There is also an Activate event that can be triggered to clear the old cache of things associated with the old service worker.

The Servcie worker can respond to requests through the FetchEvent event. You can modify the response to any of these requests by using the FetchEvent.respondWith method.

Note: Because it takes some time for onInstall and onActivate to complete, the service worker standard provides a WaitUntil method that is called when onInstall or onActivate is triggered, accepting a Promise. Functional events are not distributed to the service worker until the Promise is resolved.

Other usage scenarios

Service workers can also be used to do these things:

  • Background data synchronization
  • Respond to resource requests from other sources
  • Centrally receive computationally expensive data updates, such as geo-location and gyroscope information, so that multiple pages can leverage the same set of data
  • Compile and manage dependencies of CoffeeScript, Less, CJS/AMD modules on the client side (for development purposes)
  • Background service hook
  • Custom templates are used for specific URL patterns
  • Performance enhancements, such as prefetching resources that a user might need, such as the last few images in an album

In the future, Service Workers can be used to do more to bring the Web platform closer to native applications. It is worth noting that other standards can and will use service workers, such as:

  • Background synchronization: Start a service worker to update the cache even if no user is visiting a particular site
  • Response to push: Starts a service worker to send a message to the user notifying the user that new content is available
  • Respond to a time or date
  • Access to geofencing

interface

  • Cache

Represents the storage for a pair of Request/Response objects that is cached as part of the ServiceWorker lifecycle.

  • CacheStorage

Represents the storage of a Cache object. Provide a home directory for all named caches. ServiceWorker can access and maintain the mapping of name strings to Cache objects.

  • Client

Represents the scope of the service worker client. A service worker client can be either a document in the browser context or a sharedWorker controlled by an active Worker.

  • Clients

Represents a Client object container and is the primary way to access the active service worker clients of the current source.

  • ExtendableEvent

The extension is distributed to the Install and Activate event sequences of ServiceWorkerGlobalScope as part of the service worker lifecycle. This ensures that any functional events (such as FetchEvent) are not distributed to the ServiceWorker until it updates the database schema, removes expired cache entries, and so on.

  • ExtendableMessageEvent

Event object for message events fired on ServiceWorker (when a channel message is received from another context on ServiceWorkerGlobalScope) – prolongs the life cycle of such events.

  • FetchEvent

Pass to ServiceWorkerGlobalScope. Onfetch processing function parameters, FetchEvent represents a request in ServiceWorker ServiceWorkerGlobalScope distribution. It contains information about the result of the request and response, and provides the fetchEvent.respondWith () method, which allows us to provide an arbitrary response back to the control page.

  • InstallEvent

The InstallEvent interface represents an installation action distributed in the ServiceWorker’s ServiceWorkerGlobalScope, as a subevent of ExtendableEvent. It ensures that functional events such as FetchEvent are not distributed during installation.

  • NavigationPreloadManager

Provides a way to manage resource preloading using Service workers.

  • Navigator.serviceWorker

Returns a ServiceWorkerContainer object that provides entry for registering, deleting, updating, and communicating with the ServiceWorker in the related Document.

  • NotificationEvent

The parameter passed to the onNotificationClick handler. The NotificationEvent interface represents the click event notification that is distributed in the ServiceWorker ServiceWorkerGlobalScope.

  • ServiceWorker

Represents a service worker. Multiple browsing contexts (such as Pages, Workers, and so on) can be associated with the same ServiceWorker object.

  • ServiceWorkerContainer

Provides an object that treats service workers as a whole in the network ecosystem, including secondary registration, de-registration, and updating of service workers, and access to the status of service workers and their registration information.

  • ServiceWorkerGlobalScope

Represents the global execution context of the service worker.

  • ServiceWorkerMessageEvent

Contains information about an event that is sent to the navigator.serviceWorker target.

  • ServiceWorkerRegistration

Represents the registration of the service worker.

  • ServiceWorkerState

Associated with the state of its own ServiceWorker.

  • SyncEvent

The parameter passed to the synchronization function. The SyncEvent interface represents the synchronization action distributed by the ServiceWorker ServiceWorkerGlobalScope.

  • SyncManager

Provides an interface for registering and returning Syncregistration objects.

  • WindowClient

Represents the scope of the service worker client that is recorded in the browser context and is controlled by the active worker. Is a special type of Client object that contains some additional methods and available properties.

Learn interesting knowledge, meet interesting friends, build interesting soul!

Everybody is good! I am the author of “programming samadhi” hermit king, my public account is “programming samadhi”, welcome to pay attention to, I hope you give me more advice!