service workers 기초 및 활용 (korean)

20

Click here to load reader

Upload: jungkees

Post on 16-Jul-2015

1.379 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Service workers 기초 및 활용 (Korean)

Service Workers기초 및 활용

Page 2: Service workers 기초 및 활용 (Korean)

Jungkee SongGithub: https://github.com/jungkees Twitter: @jungkees Google+: +JungkeeSong Facebook: https://www.facebook.com/jungkees

Page 3: Service workers 기초 및 활용 (Korean)

Service Worker 가 해결하는 문제들

• 웹의 오프라인 사용성

- 오프라인 우선 (Offline-first)- 개발자가 원하는대로!

개발자가 프로그래밍을 통하여 컨트롤 하는 Cache

개발자가 직접 작성하는 HTTP request 프록시

• 백그라운드 프로세싱

- 브라우저가 실행 중이지 않을 때도 이벤트 처리를 하고 싶다!

- Push notification, System alarm, BackgroundSync …

Page 4: Service workers 기초 및 활용 (Korean)

표준개발 현황

W3C Working Draft[ED] https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html

[Github] https://github.com/slightlyoff/ServiceWorker

Page 5: Service workers 기초 및 활용 (Korean)

이벤트 기반으로 동작하는 Worker

Service Worker는 브라우저에 의해 언제든지 종료 될 수 있음

fetch event

Navigation/Resource request

onfetch

Page

SW

Cache self.caches.match(url)

Promise<response>

e.respondWith(Promise<response>)

Page Page

Navigation/Resource request

fetch event

e.respondWith(Promise<response>)

Page 6: Service workers 기초 및 활용 (Korean)

개발자가 프로그래밍으로 컨트롤 하는 Cache

Cache / CacheStorage 오프젝트 활용

Cache 오브젝트 메소드 참조

caches.open(“myCache”).then(function(cache) { … })

Page 7: Service workers 기초 및 활용 (Korean)

설계 및 동작 원리

• Same origin 기반으로 동작

• URL scope 이 registration 을 식별하는 key가 됨

• Client request 시 matching 되는 SW 에 의해 control 시작 됨

• Registration 은 installing / waiting / active worker를 가짐

• Lifecycle 이벤트: install, activate

• Functional 이벤트: fetch, push, sync 등

• Document 또는 Worker 가 Client 가 됨

• Client 가 register 를 요청하여 브라우저에 install 됨

• Resource request 시 선택된 SW 에 의해 control 됨

• HTTPS 필수

Page 8: Service workers 기초 및 활용 (Korean)

Client request

Client 가 client request 시 SW registration 을 선택함

onfetchsw.js

Cacheself.caches.match(url)

Promise<response>

e.respondWith(Promise<response>)

“/” /sw.js

[ Registration map ]Scope Script URL

“/foo/” /foo/sw.js

Page Navigate to https://example.com/index.html

fetch event

Scope matching

Run SW

Page 9: Service workers 기초 및 활용 (Korean)

Resource request

Control 되고 있는 client 는 resource request 시 해당 SW를 사용함

onfetchsw.js

Cache self.caches.match(url)

Promise<response>

e.respondWith(Promise<response>)

“/” /sw.js

[ Registration map ]Scope Script URL

“/foo/” /foo/sw.js

Page

Fetch “https://example.com/img/flower.png

fetch event

Control

Run SW

Page 10: Service workers 기초 및 활용 (Korean)

Registration

Client 에서 수행

// scope 은 default로 script의 위치와 동일한 url로 설정 됨

navigator.serviceWorker.register("/assets/v1/serviceworker.js").then( function(registration) { console.log("success!"); registration.installing.postMessage(“Howdy from your installing page."); }, function(why) { console.error("Installing the worker failed!", why); });

“/assets/v1/” /assets/v1/serviceworker.js

[ Registration map ]Scope Script URL

Page 11: Service workers 기초 및 활용 (Korean)

Registration

Client 에서 수행[ Registration map ]

Scope Script URL

navigator.serviceWorker.register(“/sw.js”, { scope: “/bar/” });

“/bar/” /sw.js

“/foo/” /foo/sw.js

“/bar/” /bar/sw.js

navigator.serviceWorker.register("/foo/sw.js", { scope: “/foo/” });

navigator.serviceWorker.register("/bar/sw.js");

Page 12: Service workers 기초 및 활용 (Korean)

Service Worker 상태 변화

Service Worker 생명주기

HTML5 Rocks Introduction to Service Worker 내용 중

서비스워커 생명주기 단락을 참조해 보자

Page 13: Service workers 기초 및 활용 (Korean)

Install 과정: oninstall / onactivate

• 브라우저가 SW에 install 이벤트를 발생 시켜줌

- 개발자가 App에 필요한 resource를 미리 Caching할 수 있는 시간

• Event handler 안에서 event.waitUntil(promise) 를 활용하여 promise를 통해 추상화 된 해당 동작이 resolve될 때까지 SW의 lifetime을 늘일 수 있음

• 브라우저가 SW에 activate 이벤트를 발생 시켜줌

- 개발자가 갱신이 필요한 resource를 정리할 수 있는 시간

Page 14: Service workers 기초 및 활용 (Korean)

oninstall

SW script fetch및 실행이 성공적으로 이루어 지면 install 이벤트가 service worker 에 dispatch 됨

Jake Archibald’s “The offline cookbook” 중

1-1/1-2 On install 참조

Page 15: Service workers 기초 및 활용 (Korean)

onactivate

waiting worker 가 activation 될 조건이 만족될 때 activate 이벤트가 service worker 에 dispatch 됨

Jake Archibald’s “The offline cookbook” 중

1-3. On activate 참조

Page 16: Service workers 기초 및 활용 (Korean)

Fetch 이벤트 핸들링: onfetch

Client / resource request 발생시 마다 fetch 이벤트가 Service Worker 에 dispatch 됨

Jake Archibald’s “The offline cookbook” 중

1-6. Stale-while-revalidate 참조

Page 17: Service workers 기초 및 활용 (Korean)

Service Worker Update 발생 경로

• navigator.serviceWorker.register() API 명시적 호출

• 브라우저에 의한 자동 Update

• 매 client request 처리 시

• register.update() API의 명시적 호출

Page 18: Service workers 기초 및 활용 (Korean)

Update 동작

모든 client가 unload 되기 전에는 기존 active worker를 그대로 사용

onfetchsw-v2

Cache self.caches.match(url)

Promise<response>

e.respondWith(Promise<response>)

“/” /sw-v1

[ Registration map ]Scope active

fetch event

-

waiting

Page

sw-v1

Update

Install

Page

sw-v1 /sw-v2 /sw-v2-

Page

sw-v2

Fetch “https://example.com/img/flower.png

Run SW

Page 19: Service workers 기초 및 활용 (Korean)

브라우저 지원 현황

Chrome 40+

Firefox nightly

Under consideration

40에서는 Cache, Client 지원하지 않음

IE

Partial under flagabout:config > dom.serviceWorkers.enabled

Jake’s “Is ServiceWorker ready?”

Stay alerted!

Cache polyfill 활용 가능