Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the introduction to Service Worke in JavaScript API?

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Service Worker JavaScript API introduction is how, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.

What is service worker?

Service Worker is a WEB API proposed and pushed by the Chrome team to provide advanced and sustainable background processing capabilities for web applications. The WEB API standard was drafted in 2013 and incorporated into the W3C WEB draft standard in 2014, which is still in the draft stage.

The main feature of Service Worker is that after it is registered and installed successfully in the page, it runs in the background of the browser, is not affected by the page refresh, and can monitor and intercept HTTP requests of all pages within the scope.

Similar to the role of a middleman between the server and the browser, if service worker is registered in the website, it can intercept all the requests of the current website and make a judgment (you need to write a corresponding judgment procedure). If you need to make a request to the server, transfer it to the server. If you can directly use the cache, you can directly return the cache and no longer transfer it to the server. As a result, the browsing experience is greatly improved.

Service Worker enables a set of features that were previously proprietary to native applications. The first draft of Service Worker was released in 2014 and is now supported by all major browsers.

As has been pointed out, Service Worker is a network agent. This means that they can control all network requests on the page and can be programmed to respond with cached ones.

Characteristics of Service Worker

The website must use HTTPS. Except when debugging using the local development environment (such as domain name using localhost)

Running in the background of the browser, you can control all page requests under the open scope

Separate scope, separate runtime environment, and execution thread

Cannot manipulate page DOM. But it can be handled through the event mechanism.

How to register for Service Worker

It doesn't take much code to register Service Worker, just a JS file for Service Worker code, which is generally named service-worker.js

/ / first check whether the browser supports Service Worker if ('serviceWorker' in navigator) {navigator.serviceWorker (' / sw/service-worker.js'). Then (function (registration) {console.log (registration);}) .catch (function (err) {console.log (err);});}

In fact, there is only one line of key code:

Navigator.serviceWorker.register ('/ sw/service-worker.js')

Note:

The registration path of Service Worker determines the default scope of its scope. In the example, service-worker.js is under the / sw path, which makes the Service Worker receive only fetch events under the / sw path by default. If you store it under the root path of a site, you will receive all fetcg events for that site.

If you want to change its scope, set the scope range in the second parameter. In the example, it is changed to the root directory, which takes effect for the entire site.

You should also be aware that Service Worker has no concept of page scope, and all page requests within scope are monitored by the currently active Service Worker.

What features can be enabled by Service Worker?

In this section, I'll go into more detail about the functionality of Service Worker, including some small code examples.

Service workers enable the following features, which are also the core of PWA:

Offline function

Regular background synchronization

Push Notification

Offline function

Service Worke provides offline functionality by caching resources and intercepting network requests, which can be used with previously cached resources rather than rerequesting the server.

We can draw two steps from this:

Pre-cache

Processing requests from the cache

Both steps take advantage of Cache API, which is used by Web Workers and browsers, and provides us with a storage mechanism for network requests.

LocalStorage access to Web and service staff contexts is blocked to prevent concurrency issues. As an alternative, IndexedDB can be used to store large amounts of data.

Pre-cache

Precaching is a term that describes downloading and caching files before Service Worker is activated. It is done in the "install" step of the Service Worker life cycle. Once Service Worker is active, it is ready to service the files in the cache.

Typically, we cache Application Shell, which is the minimum amount of code required to run the site. If you develop a native application, this is the code package you will upload to the app store. This includes all the necessary basic JavaScript,HTML and pictures.

Self.addEventListener ('install', function (event) {event.waitUntil (caches.open (currentCache.offline). Then (function (cache) {return cache.addAll ([' / static/images/offline.svg','/ static/html/offline.html',]););})

Processing requests from the cache

At this stage, we have stored all the application code in the cache, and Service Worker is already active, that is, running in the browser background.

The only thing missing now is listening for fetch events and returning results from the cache. Through the fetch event, you can intercept http/https requests within the current scope and give your own response. Combined with Fetch API, we can easily deal with the request response and realize the control of the network request.

Self.addEventListener ('fetch', function (event) {event.respondWith (caches.match (event.request). Then (function (response) {return response | | fetch (event.request);});})

In this example, we respond with cached content as much as possible. As a fallback, we send out a network request.

Here, a policy logic of cache priority and degradation is implemented: monitor all http requests, and directly return the contents of the cache when the requested resources are already in the cache; otherwise, use fetch API to continue the request, and add images or css or js resources to the cache when the request is successful; if the request is offline or an error occurs, the downgrade returns the pre-cached offline content.

Regular background synchronization

As already mentioned in the introduction, Service Worker runs on a separate thread with other service workers, so they can execute their code even if the page is closed. This feature is important for performing background synchronization and providing push notifications.

Background synchronization

After the user leaves the page, background synchronization is usually used to synchronize data.

For example, after editing a document on a mobile phone, we click "Save" and leave the page after we finish writing. If the connection is disconnected while editing the document, we must wait for the connection to resume before we can save the document.

The purpose of background synchronization is to solve this problem and automatically send data once the connection is re-established.

Let's look at an example:

App.js

Navigator.serviceWorker.ready.then ((registration) = > {return registration.sync.register ('sync-save-document');})

Service-worker.js

Self.addEventListener ('sync', (event) = > {if (event.tag =' sync-save-document') {event.waitUntil (saveDocument ());}})

SaveDocument is a return Promise, and if rejected (for example, due to network problems), synchronization will automatically retry.

One thing to note is that the synchronization tag must be unique. For example, if I want to schedule five "message" type background synchronizations, only the last one will pass. Therefore, in this case, each label should have a unique identifier.

Regular background synchronization

Regular background synchronization solves problems different from normal background synchronization. The API can be used to update data in the background without waiting for the user.

This is useful for many applications. With this technology, users can read the latest news articles without an Internet connection.

To prevent abuse of this feature, the frequency of synchronization depends on the site participation score set by the browser for each site. If you often open a web app, the frequency can be up to 12 hours.

One requirement to achieve this is that the site has been installed and added to the home screen as a PWA on a mobile device.

Push Notification

Another native-like feature of Service Worker is push notifications. We usually know about them in the form of text messages or social media notifications, but they can also be used on desktop computers.

All major browsers except Safari support them, while Safari has its own implementation of desktop applications.

To use push notifications, you need to set up a server that pushes notifications to all clients. Because Service Worker runs on another thread in the background, the user can see the push notification even if the page is not currently open.

There are two steps to the implementation of push:

Different browsers need to use different push message servers. Taking the use of Google Cloud Messaging as a push service on Chrome as an example, the first step is to register applicationServerKey (obtained through GCM registration) and subscribe or initiate subscriptions on the page. Each session has a separate endpoint (endpoint), and the PushSubscription.endpoint of the subscription object is the endpoint value. After sending the endpoint to the server, the server uses this value to send a message to the active Service Worker of the session (communicating with the browser client through GCM).

Browser support

With the exception of Safari and IE/Edge, most modern browsers are already supported.

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report