현재 번역은 완벽하지 않습니다. 한국어로 문서 번역에 동참해주세요.

 

Service worker는 기본적으로 웹 응용 프로그램, 브라우저 및 네트워크 (사용 가능한 경우) 사이에있는 프록시 서버의 역할을합니다. 또한 효과적인 오프라인 환경을 만들고 네트워크 요청을 가로 채고 네트워크 사용 가능 여부에 따라 적절한 조치를 취하고 서버에있는 자산을 업데이트하기위한 것입니다. 또한 푸시 알림 및 백그라운드 동기화 API에 대한 액세스를 허용합니다.

Service worker의 개념과 사용법

service worker는 출발지와 경로에 대해 등록 된 이벤트 중심 worker입니다. 연결된 웹 페이지 / 사이트를 제어하고 탐색 및 리소스 요청을 가로 채어 수정하며 리소스를 매우 세부적으로 캐싱하여 특정 상황에서 앱의 동작 방식을 완벽하게 제어 할 수있는 JavaScript 파일 형식을 취합니다 , 네트워크를 사용할 수 없는 경우에 역할이 확실해집니다.

service worker는 작업자 컨텍스트(worker context)에서 실행되기 때문에 DOM 액세스가 없으며 앱에 권한을 부여하는 기본 JavaScript와는 다른 스레드에서 실행되므로 차단되지 않습니다. 완전 비동기로 설계되었습니다. 결과적으로 동기식 XHRlocalStorage와 같은 API를 서비스 작업자 내부에서 사용할 수 없습니다.

 

서비스 작업자는 보안상의 이유로 HTTPS를 통해서만 실행됩니다. 네트워크 요청을 수정하면 중간 공격에서 사람에게 크게 개방 될 수 있습니다. Firefox에서는 Service Worker API도 숨겨져있어 사용자가 private browsing mode에있을 때 사용할 수 없습니다.

Note: Service Workers win over previous attempts in this area such as; AppCache because they don't make assumptions about what you are trying to do, and then break when those assumptions are not exactly right; you have granular control over everything.

Note: Service worker는 일반적으로 응답이 오기를 기다릴 것이므로 promises를 많이 사용합니다. 그 후에 응답자는 성공 또는 실패 조치로 응답합니다. 이를 위해 promise 아키텍처를 사용하는 것이 좋습니다.

Registration

service worker는 ServiceWorkerContainer.register () 메소드를 사용하여 등록됩니다. 성공하면 서비스 작업자가 클라이언트에 다운로드되고 전체 원본 또는 사용자가 지정한 하위 집합 내에서 사용자가 액세스 한 URL에 대한 설치 / 활성화 (아래 참조)를 시도합니다.

Download, install and activate

이 시점에서 service worker는 다음과 같은 수명주기를 가집니다.

  1. Download
  2. Install
  3. Activate

service worker는 사용자가 service worker가 제어하는 ​​사이트 / 페이지에 처음 액세스 할 때 즉시 다운로드됩니다.

그 후 24 시간마다 다운로드됩니다. 더 자주 다운로드 될 수 있지만 잘못된 스크립트 때문에 너무 오래 걸리는 것을 방지하기위해 24 시간마다 다운로드해야합니다.

다운로드 한 파일이 기존 service worker와 다르거나(바이트 단위로 비교 한 경우) 페이지(사이트)의 첫 번째 service worker와 만난 경우 설치가 시도됩니다.

service worker가 다운로드 되면 설치가 시작되고 설치가 완료된 후 service worker가 활성화됩니다.

사용 가능한 기존 service worker가 있는 경우 새 버전이 백그라운드에 설치되지만 아직 활성화되지 않습니다. 이 시점에서 새로운 service worker를 대기중인 작업자라고합니다. 이전 service worker를 계속 사용중인 페이지가 로드되지 않은 경우에 활성화됩니다. 로드 할 페이지가 더 이상 없으면 새로운 service worker가 활성화됩니다 (활성 작업자가 됨). Activation can happen sooner using ServiceWorkerGlobalScope.skipWaiting() and existing pages can be claimed by the active worker using Clients.claim().

You can listen out for the InstallEvent; a standard action is to prepare your service worker for usage when this fires, for example by creating a cache using the built in storage API, and placing assets inside it that you'll want for running your app offline.

 

또한 activate 이벤트가 있습니다. 이 이벤트가 발생할 때 이전 버전의 Service worker와 관련된 이전 캐시 및 기타 항목을 정리하기 좋습니다.

Your service worker can respond to requests using the FetchEvent event. You can modify the response to these requests in any way you want, using the FetchEvent.respondWith method.

Note: Because oninstall/onactivate could take a while to complete, the service worker spec provides a waitUntil method, once this is called oninstall or onactivate, it passes a promise. Functional events are not dispatched to the service worker until the promise is successfully resolved.

For a complete tutorial to show how to build up your first basic example, read Using Service Workers.

Other use case ideas

Service workers are also intended to be used for such things as:

  • Background data synchronization
  • Responding to resource requests from other origins
  • Receiving centralized updates to expensive-to-calculate data such as geolocation or gyroscope, so multiple pages can make use of one set of data
  • Client-side compiling and dependency management of CoffeeScript, less, CJS/AMD modules, etc. for dev purposes
  • Hooks for background services
  • Custom templating based on certain URL patterns
  • Performance enhancements, for example pre-fetching resources that the user is likely to need in the near future, such as the next few pictures in a photo album.

In the future, service workers will be able to do a number of other useful things for the web platform that will bring it closer towards native app viability. Interestingly, other specifications can and will start to make use of the service worker context, for example:

  • Background synchronization: Start up a service worker even when no users are at the site, so caches can be updated, etc.
  • Reacting to push messages: Start up a service worker to send users a message to tell them new content is available.
  • Reacting to a particular time & date
  • Entering a geo-fence

Interfaces

Cache
Represents the storage for Request / Response object pairs that are cached as part of the ServiceWorker life cycle.
CacheStorage
Represents the storage for Cache objects. It provides a master directory of all the named caches that a ServiceWorker can access, and maintains a mapping of string names to corresponding Cache objects.
Client
Represents the scope of a service worker client. A service worker client is either a document in a browser context or a SharedWorker, which is controlled by an active worker.
Clients
Represents a container for a list of Client objects; the main way to access the active service worker clients at the current origin.
ExtendableEvent
Extends the lifetime of the install and activate events dispatched on the ServiceWorkerGlobalScope, as part of the service worker lifecycle. This ensures that any functional events (like FetchEvent ) are not dispatched to the ServiceWorker, until it upgrades database schemas, and deletes outdated cache entries, etc.
ExtendableMessageEvent
The event object of a message event fired on a service worker (when a channel message is received on the ServiceWorkerGlobalScope from another context) — extends the lifetime of such events.
FetchEvent
The parameter passed into the ServiceWorkerGlobalScope.onfetch handler, FetchEvent represents a fetch action that is dispatched on the ServiceWorkerGlobalScope of a ServiceWorker. It contains information about the request and resulting response, and provides the FetchEvent.respondWith() method, which allows us to provide an arbitrary response back to the controlled page.
InstallEvent
The parameter passed into the oninstall handler, the InstallEvent interface represents an install action that is dispatched on the ServiceWorkerGlobalScope of a ServiceWorker. As a child of ExtendableEvent, it ensures that functional events such as FetchEvent are not dispatched during installation.
NavigationPreloadManager
Provides methods for managing the preloading of resources with a service worker.
Navigator.serviceWorker
Returns a ServiceWorkerContainer object, which provides access to registration, removal, upgrade, and communication with the ServiceWorker objects for the associated document.
NotificationEvent
The parameter passed into the onnotificationclick handler, the NotificationEvent interface represents a notification click event that is dispatched on the ServiceWorkerGlobalScope of a ServiceWorker.
ServiceWorker
Represents a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same ServiceWorker object.
ServiceWorkerContainer
Provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister, and update service workers, and access the state of service workers and their registrations.
ServiceWorkerGlobalScope
Represents the global execution context of a service worker.
ServiceWorkerMessageEvent
Represents a message sent to a ServiceWorkerGlobalScopeNote that this interface is deprecated in modern browsers. Service worker messages will now use the MessageEvent interface, for consistency with other web messaging features.
ServiceWorkerRegistration
Represents a service worker registration.
ServiceWorkerState
Associated with its ServiceWorker's state.
SyncEvent

The SyncEvent interface represents a sync action that is dispatched on the ServiceWorkerGlobalScope of a ServiceWorker.

SyncManager
Provides an interface for registering and listing sync registrations.
WindowClient
Represents the scope of a service worker client that is a document in a browser context, controlled by an active worker. This is a special type of Client object, with some additional methods and properties available.

Specifications

Specification Status Comment
Service Workers Working Draft Initial definition.

Browser compatibility

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 40 17 44.0 (44.0)[1] No support 24 No support[2]
install/activate events 40 17 44.0 (44.0)[1] No support (Yes) No support
fetch event/request/
respondWith()
40 17 44.0 (44.0)[1] No support No support No support
caches/cache 42 17 39.0 (39.0)[1] No support No support No support
ServiceWorkerMessageEvent deprecated in favour of MessageEvent 57 No support 55.0 (55.0)[1] No support No support No support
NavigationPreloadManager 59 No support   No support 46 No support
Feature Android Webview Chrome for Android Edge Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
Basic support No support 40 17 44.0 (44.0) No support (Yes) No support[2]
install/activate events No support 40 17 44.0 (44.0) No support (Yes) No support
fetch event/request/
respondWith()
No support 40 17 44.0 (44.0) No support No support No support
caches/cache No support 40 17 39.0 (39.0) No support No support No support
ServiceWorkerMessageEvent deprecated in favour of MessageEvent No support

57

No support 55.0 (55.0) No support No support No support
NavigationPreloadManager No support 59 No support No support No support 46 No support

[1] Service workers (and Push) have been disabled in the Firefox 45 & 52 Extended Support Releases (ESR.)

[2] This feature is supported in Safari Technology Preview.

See also

문서 태그 및 공헌자

이 페이지의 공헌자: limkukhyun, chrisdavidmills
최종 변경: limkukhyun,