Home>Article>Web Front-end> Detailed explanation of Service Workers in javascript!

Detailed explanation of Service Workers in javascript!

青灯夜游
青灯夜游 forward
2020-12-03 17:44:24 3911browse

This article will introduce you to JavaScript API - Service Workers. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Detailed explanation of Service Workers in javascript!

Related recommendations: "Introduction to Programming"

What is service worker

Service Worker is proposed by the Chrome team A WEB API recommended by Heli 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 standard draft in 2014. It is currently in the draft stage.

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

Similar to the role of a middleman between the server and the browser, ifservice workeris registered in the website, it can intercept all requests from the current website and make judgments (corresponding judgment programs need to be written) ), if a request needs to be made to the server, it will be forwarded to the server. If the cache can be used directly, it will be directly returned to the cache and will not be forwarded to the server. This greatly improves the browsing experience.

Detailed explanation of Service Workers in javascript!

Service Workerenables a set of features that were previously exclusive to native applications. The first draft of Service Workers was released in 2014, and all major browsers now support them.

Like the definition already pointed out,Service Workeris a network proxy. This means they have control over all network requests within the page and can program them to use cached responses.

Service Worker Features

  • The website must useHTTPS. In addition to using the local development environment for debugging (such as the domain name usinglocalhost)
  • Running in the browser background, you can control all page requests under the opened scope
  • separately The scope of scope, separate running environment and execution thread
  • cannot operate the page DOM. But it can be handled through the event mechanism

How to register Service Worker

Registering Service Worker does not require much code, only one forService Workercode JS file, usually namedservice-worker.js

// 首先检查浏览器是否支持 Service Worker if ('serviceWorker' in navigator) { navigator.serviceWorker .register('/sw/service-worker.js') .then(function(registration) { console.log(registration); }) .catch(function(err) { console.log(err); }); }

In fact, the key code is only one line:

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

Note:

# The registration path of

##Service Workerdetermines itsscopedefault scope. In the example,service-worker.jsis under the/swpath, which makes the Service Worker only receiveunder the/swpath by default. fetchevent. If stored in the root path of the website, allfetcgevents of the website will be received.

If you want to change its scope, you can set the

scopescope 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 of this: Service Worker has no concept of page scope, and all page requests within the scope will be monitored by the currently activated Service Worker.

What functions can Service Worker enable?

In this section, I will go into further detail about the capabilities of Service Worker, including some small code examples.

Service workers enable the following features, which are also core to

PWA:

    Offline features
  • Regular background synchronization
  • Push notifications
Offline functionality

Service Worke provides offline functionality by caching resources and intercepting network requests, which can be used with previously cached resources instead of re-requesting them server.

We can derive two steps from this:

    Pre-caching
  • Process the request from the cache
These two steps Both take advantage of the Cache API, which is used by Web Workers and browsers and provides us with a storage mechanism for network requests.

Access to

localStoragefor web and service worker contexts is blocked to prevent concurrency issues. As an alternative,IndexedDBcan be used to store large amounts of data.

Precaching

Precachingis a term that describes downloading and caching files before a Service Worker is active. It is done during the "install" step of the Service Worker life cycle. Once the service worker is active, it will be ready to serve files from the cache.

Normally, we want to cache the

Application Shell, which is the minimum amount of code required to run the website. If you developed a native app, this is the package of code you would upload to the app store. This includes all required basic JavaScript, HTML and images.

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', ]); }); ); });

Handle requests from cache

在此阶段,我们已经将所有应用程序代码存储在缓存中,并且Service Worker已处于激活即运行于浏览器后台。

现在唯一缺少的是监听fetch事件并从缓存中返回结果。可以通过fetch事件可以拦截到当前作用域范围内的 http/https 请求,并且给出自己的响应。结合Fetch API,可以简单方便地处理请求响应,实现对网络请求的控制。

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

在本例中,我们尽可能使用缓存的内容进行响应。作为回退,我们发出一个网络请求。

这里实现了一个缓存优先降级处理的策略逻辑:监控所有http请求,当请求资源已经在缓存里了,直接返回缓存里的内容;否则使用fetchAPI 继续请求,如果是 图片或cssjs资源,请求成功后将他们加入缓存中;如果是离线状态或请求出错,则降级返回预缓存的离线内容。

定期后台同步

正如在引言中已经提到的那样,Service Worker与其他服务工作者在一个单独的线程上运行,所以即使关闭页面,它们也可以执行其代码。 此功能对于执行后台同步和提供推送通知很重要。

后台同步

用户离开页面后,后台同步通常用于同步数据。

例如,在手机上编辑文档后,我们写完会点击“保存”并离开页面。 如果在编辑文档期间连接断开,我们必须等待连接恢复才能保存文档。

后台同步的目的是解决这个问题,一旦连接重新建立,自动发送数据。

来看一个示例:

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是一个返回Promise,如果被拒绝(例如由于网络问题),同步将自动重试。

要注意的一件事是,同步标记必须是唯一的。 例如,如果我要安排5个“message”类型的后台同步,则只有最后一个会通过。 因此,在这种情况下,每个标签都应具有唯一的标识符。

定期后台同步

定期后台同步解决与正常后台同步不同的问题。 该API可用于在后台更新数据,而不必等待用户。

这对很多应用程序都很有用。有了这项技术,用户可以在没有互联网连接的情况下阅读最新的新闻文章。

为了防止滥用这一功能,同步的频率取决于浏览器为每个网站设置的站点参与度分数。如果你经常打开一个网页应用,这个频率最多可以达到12个小时。

要实现此目的一个要求是,该网站已作为移动设备上的PWA安装并添加到主屏幕。

推送通知

Service Worker另一个类似本机的特性是推送通知。我们通常通过手机短信或社交媒体通知的形式知道它们,但它们也可以在台式电脑上使用。

Safari之外,所有主流浏览器都支持它们,而Safari对桌面应用程序有自己的实现。

要使用推送通知,需要设置一台服务器,该服务器会将通知推送给所有客户端。 由于Service Worker在后台在另一个线程上运行,因此即使页面当前未打开,用户也可以看到推送通知。

推送的实现有两步:

不同浏览器需要用不同的推送消息服务器。以 Chrome 上使用Google Cloud Messaging作为推送服务为例,第一步是注册applicationServerKey(通过 GCM 注册获取),并在页面上进行订阅或发起订阅。每一个会话会有一个独立的端点(endpoint),订阅对象的属性(PushSubscription.endpoint) 即为端点值。将端点发送给服务器后,服务器用这一值来发送消息给会话的激活的 Service Worker (通过 GCM 与浏览器客户端沟通)。

浏览器支持情况

Detailed explanation of Service Workers in javascript!

除了 Safari 和 IE/Edge,大部分现代浏览器都已经得到了支持。

总结

希望通过本文介绍基本概念和特性,可以让你更好地理解Service Worker

英文原文地址:https://felixgerschau.com/service-workers-explained-introduction-javascript-api/

作者: Felix Gerschau

译文地址:https://segmentfault.com/a/1190000027080988

想要查阅更多相关文章,请访问PHP中文网!!

The above is the detailed content of Detailed explanation of Service Workers in javascript!. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete