什么是React JS中的Service Worker

创建React应用时,默认情况下会调用Service Worker。为什么要使用服务人员?默认调用的原因是什么?

Sam小哥理查德2020/03/16 10:05:06

In simple and plain words, it’s a script that browser runs in the background and has whatsoever no relation with web pages or the DOM, and provide out of the box features. It also helps you cache your assets and other files so that when the user is offline or on slow network.

Some of these features are proxying network requests, push notifications and background sync. Service workers ensure that the user has a rich offline experience.

You can think of the service worker as someone who sits between the client and server and all the requests that are made to the server pass through the service worker. Basically, a middle man. Since all the request pass through the service worker, it is capable to intercept these requests on the fly.

在此处输入图片说明

理查德阿飞2020/03/16 10:05:06

您的应用程序可能不需要服务人员。如果要使用create-react-app创建项目,则默认情况下会调用该项目

服务人员在很好的解释这个文章。总结一下

A service worker是一个脚本,您的浏览器在后台运行,与网页分开,为不需要网页或用户交互的功能打开了大门。如今,它们已经包含了诸如push notificationsbackground sync和具有的功能 ability to intercept and handle network requests,包括 programmatically managing a cache of responses

将来,服务人员可能会支持诸如periodic sync或的其他功能 geofencing

根据此PR创建反应应用

Service workers通过create-react-app引入 SWPrecacheWebpackPlugin

Using a server worker with a cache-first strategy offers performance advantages, since the network is no longer a bottleneck for fulfilling navigation requests. It does mean, however, that developers (and users) will only see deployed updates on the "N+1" visit to a page, since previously cached resources are updated in the background.

The call to register service worker is enabled by default in new apps but you can always remove it and then you’re back to regular behaviour.