현실적 pwa
TRANSCRIPT
25th August, 2016 Jae Sung Park
[Image source] https://www.ickr.com/photos/sunset_man/4591376374/
현실적PWA
PWA?"Progressive Web Applications take advantage ofnew technologies to bring the best of mobile sites
and native applications to users" - Progressive Web Apps
Instant Loading: , ,
Add to Home Screen:
Push-notications: ,
Service Workers Background Sync API Cache API
Web App Manifest
Push API Notications API
Performance mattersPWA 기술들 중, 가장 중요한 요소는 바로 oine caching!
캐싱은 왜 중요한가?오프라인 지원성능 향상 네트워크 보다 캐시를 통해 요청받는 것이 빠르기 때문Lie-Fi
Lie-Fi"Indicates that you are connected to a wirelessnetwork, however you are still unable to load
webpages" - urban dictionary
[참고]: What is lie-?
The challenges of PWAiOS 미지원
: Under ConsiderationWeb App Manifest?Push & Notication API?
데스크탑 브라우저? (Service Worker 기준)
IE (Not Supported), (In Development) (Under Consideration)
(Supported)
Service Workers
EdgeSafariFireFox
브라우저의 가 문제. 캐싱을 모든 환경에서 사용할 순 없을까?
지원 범위
그런데... 잠깐.브라우저는 이미 캐싱하고 있지 않나?
사용자가 방문하는 웹사이트의 모든 리소스들에 대해 브라우저는 로컬 캐시해 다음 방문시 로컬 캐시된 리소스를 활용하도록 처리된다.
그러나 많은 경우(온라인 상태인 경우라도) 로컬 캐시된 리소스를 활용하지 못하는 경우가 발생한다.
물론, 오프라인인 경우에는 로컬 캐싱은 사용불가
Cache로컬 캐시에 대하여
캐시의 상태Status Descriptionrstvisit
첫 방문인 경우, 당연히 캐싱되어 있는 리소스는 존재하지 않음
cleared 캐싱되어 있는 경우라도, 사용자가 직접 캐시를 비우거나, 백신으로 인해 지워지거나 또는 브라우저의 버그로 제거되기도 한다. (약 19%의 Chrome 사용자들의 경우, 최소 1주일에 한번 이상 버그로 인해 캐시가 지워진다. - )
purged 로컬 캐시의 공간은 모든 웹사이트가 공유해 사용하기 때문에 한정된 공간으로 인해 이전에캐시된 내용은 새로운 캐시 저장을 위해 지워지게 된다.
expired 약 69%의 리소스들은 캐싱에 대한 헤더가 없거나 또는 1일 미만의 값으로 설정되어 있다. 캐싱 기간이 만료되면, 로컬에 저장된 캐시의 내용이 유효하더라도 새롭게 요청되어 진다. (
)
revved 이전 방문으로 인해 캐싱이 되어 있는 상태라고 해도, 사이트의 내용이 변경되어 사용자의 로컬 캐시된 리소스와 달라 사용되지 못할 수도 있다.
참고
참
고
페이스북 사례페이스북에 접속하는 사용자들 중 로컬 캐시가 없는
상태의 요청 비율은 25.5% 라고 한다. (2015/04 기준)
Type Request rate of missing cache
Desktop 24.8%
Mobile 26.9%
[참고]: Web performance: Cache e忁ciency exercise
브라우저의 캐시 공간로컬 캐싱은 성능에 큰 영향을 주는 요소 중 한 가지.
그러나 모바일 환경에서의 캐싱은 데스크탑 브라우저에 비해 적은 공간을 사용
브라우저에 따라 최대 사용공간은 다르며, 잘 문서화 되어 있지 않아 정확한 limit을 확인하기는 어렵다.
종류 크기
데스크탑 3자리 수 이상 (또는 사용 디스크 전체 크기의 일부) ex. IE9의 경우는 디스크 크기의 1/256
모바일 2자리 수 정도의 공간을 활용하는 것으로 알려져 있음 ex. Android 2.x의 경우는 최대 캐시 크기는 5.7MB에 불과 (iOS의 경우는 50MB 이상)
[참고]: Early ndings: Mobile browser cache persistence and behaviour
ServiceWorkers
손쉽게 사용할 수 있는 도구들
sw-precache빌드 기반의 리소스 프리캐싱
캐싱 리소스 파일의 컨텐츠에 기반해 해쉬를 통한 자동 버저닝변경이 감지되면, 이전 버전을 만료시키고, 새로운 버전을 fetch 하도록 SW를 생성변경되지 않은 캐시 요소에 대해선 그대로 유지cache-rst strategy
sw-precacheex. Gulp task:
gulp.task('precache', function(callback) var path = require('path'); var swPrecache = require('swprecache'); var rootDir = 'demo/pwa';
swPrecache.write(path.join(rootDir, 'sw.js'), staticFileGlobs: [ rootDir + '/**/*.js,html,css,png,jpg,gif' ], stripPrefix: rootDir
// 런타임 캐싱 사용시, 생성되는 sw.js에 swtoolbox가 자동으로 포함 // https://github.com/GoogleChrome/swprecache#runtimecachingarrayobject /*,runtimeCaching: [ urlPattern: /\.cloudflare\.com\/(.*)/i, handler: 'fastest', options: cache: maxEntries: 10, name: 'cdnjs' ]*/ , callback);
[코드랩]: Adding a Service Worker with sw-precache
sw-toolbox런타임 요청에 대한 공통의 캐싱 패턴을 제공
다음의 3가지 패턴(전략*)을 제공
cacheFirstnetworkFirstfastest
// URL 패턴에 매칭되는 리소스에 대한 캐싱 전략을 지정 toolbox.router.get("/images", toolbox.[ cacheFirst | networkFirst | fastest ], options);
*The oine cookbook
sw-toolbox(global => 'use strict';
// swtookbox 로딩 importScripts('./js/swtoolbox.js');
// 디버깅을 위한 로깅 옵션 (개발자 도구 콘솔에 로깅됨) global.toolbox.options.debug = true;
// 이미지 폴더로 요청되는 리소스 toolbox.router.get('/demo/pwa/img/(.*)', global.toolbox.cacheFirst, cache: name: 'img', maxEntries: 10, maxAgeSeconds: 60*60*24 // 1일간 유효 );
// cloudflare.com (cdnjs.com)에서 요청되는 모든 리소스 toolbox.router.get('/(.*)', global.toolbox.cacheFirst, cache: name: 'cdnjs',
Instant Loading with Service Workers (Chrome Dev Summit 2015)Service Worker Toolbox, Totally Tooling Tips
Getting started with the sw-toolbox
offline-plugin for webpackwebpack 프로젝트에서 사용할 수 있는 플러그인
1) webpack.cong 설정var OfflinePlugin = require('offlineplugin');
module.exports = plugins: [ // ... other plugins // 플러그인들 중, 가장 마지막에 추가 new OfflinePlugin( caches: main: ['external.js', ':rest:'] , externals: ['external.js'], excludes: ['main.js'] ) ] // ...
2) in your client scriptrequire('offlineplugin/runtime').install();
무엇을 캐싱해야 할까?Application Shell architecture
SW가 지원되지 않는 환경에선?
스토리지를 활용한 캐싱: Web Storage, IndexedDB, File API, etc.
[참고]: Oine Storage for Progressive Web Apps
웹 스토리지를 활용한 캐싱 방법캐시의 상태에 따라 항상 모든 static 파일들이 사용자의 로컬 영역에 존재한다는 보장은 없기 때문에, 자주 변경이 되지 않는 파일에 대해서는
localStorage를 이용해 확실하게 캐싱되도록 처리하는 방법도 고려할 수 있다.
몇가지 고려사항 :자주 변경을 필요로 하지 않는 기본 라이브러리들로 대상을 한정자주 변경되지 않더라도, 업데이트가 필요할 수 있기 때문에 '버전관리' 필요localStorage는 브라우저에 따라 최대 저장용량이 다를 수 있다. 대체로 5MB 까지 저장할 수 있지만, 보다 정확한 최대치 확인필요
[데모]: 네이버 검색 활용 예
로딩 전략initializer: 스토리지 버전과 비교
storage.VER == le.VER ? load from Storage : load from File
// 스토리지에 저장된 스크립트를 evaluation 한다. let load = (code = "") => let s = document.createElement("script"); s.charset = "utf8"; s.text = code; (document.head || document.getElementsByTagName("head")[0]).appendChild(s); ;
조건과 상황에 따라 다르지만, 기존 대비 25% 성능향상 경험
How much can be stored?크롬의 경우 :
영역을 사용Per origin (not per API)Web Storage, App Cache, File System, IndexedDB, WebSQL가 공유그러나 Web Storage는 5MB로 고정
temporary
Browser LimitsFirefox No limits (prompt after 50MB)
Mobile Safari 50MB max
Desktop Safari unlimited (prompts after 5MB)
IE10+ 250MB max (prompts at 10MB)
Chrome Quota Sizenavigator.webkitTemporaryStorage.queryUsageAndQuota ( (usedBytes, grantedBytes) => console.log('Using ', usedBytes, ' of ', grantedBytes, 'bytes'), e => console.log('Error', e) );
(2016/6/16~17) : BlinkOn 6 conference State of Oine Storage APIs
Type Previous Current WorkPool (free space –
chrome's current usage) / 3xed % of total disk space: (drive size - OS size) * P
Origin quota pool size / 5 pool size / N
PWA gets at most 6% of free space on device
[참고]: , Browser Storage Abuser Oine Storage for Progressive Web Apps
Debug PWA크롬 개발자 도구
PWA 디버깅SW는 'https' 에서만 동작한다.
그러나 디버깅 용도를 위해 및 에서도 동작 (포트 상관없음)
http://localhost http://127.0.0.1
Chrome DevTools > Application Tab:
ManifestService WorkersCache
chrome://serviceworker-internals/ Debug Progressive Web Apps Service Worker
Debugging
Manifest전체 outline 확인homescreen 이벤트 에뮬레이션
Service Workers네트워크 핸들링에뮬레이션: , update/unregister swstart/stop sw
Push a notication Sync event
Cache캐시된 리소스의 확인
모든 캐시의 삭제는 Application > Clear storage
Resources (오페라에서 아카이빙한 PWA 앱 목록)
Google Developers: Google Developers: Mozilla Service Workers 101:
(PWA 리소스 큐레이션)
https://pwa.rocks/Progressive Web AppsSW Case Studies
Service Worker CookbookSW Infographic
The Service Worker LifecycleAwesome Progressive Web AppsProgressive Web App Dev Summit 2016
Gracias[Image source] https://www.ickr.com/photos/joshezzellphotography/12429005735/