PWA 정리(2): 구성 요소
교재: Do it! 프로그레시브 웹앱 만들기 - 실습 github
연관 포스트:
웹앱 매니페스트
- 앱 소개 정보와 기본 설정을 담은 JSON
{ "name": "안녕하세요! PWA by JS", "short_name": "PWA by JS", "description": "PWA start program", "scope":".", "start_url":"./", "display":"fullscreen", "orientation": "portrait", "theme_color":"#ffffff", "backgroud_color":"#ffffff", "icons":[ { "src": "images/icons/android-chrome-512x512.png", "sizes":"512x512", "type":"image/png" } ] }
서비스 워커 with js
- 캐시, 푸시 알림, 웹 API과 연동 등에 사용
캐시
- install : 캐시 파일 저장
- activate : 업데이트, 기존 캐시 제거
- fetch : 오프라인 때 캐시 읽기
- 구체적인 코드
const sCacheName = 'hello-pwa-v1'; const aFilesToCache = [ './', './index.html', './manifest.json', './images/hello-pwa.png', './images/icons/android-chrome-192x192.png', './images/icons/favicon.ico' ]; // 서비스 설치 및 캐시 저장 self.addEventListener('install', pEvent => { pEvent.waitUntil( caches.open(sCacheName) .then(pCache => { console.log('파일을 캐시에 저장함!'); return pCache.addAll(aFilesToCache); }) ) }); //고유 번호 할당받은 서비스 워커 작동 self.addEventListener('active', pEvent => { console.log('서비스워커 동작 시작됨') }); // 데이터 요청 받으면 네트워크 또는 캐시에서 찾아서 반환 self.addEventListener('fetch', pEvent => { pEvent.respondWith( caches.match(pEvent.request) .then(response => { if (!response) { console.log('네트워크에서 데이터 요청', pEvent.request); return fetch(pEvent.request) } console.log('캐시에서 데이터 요청', pEvent.request); return response; }).catch(err => console.log(err)) ); });