블로그 이미지
윤영식
Full Stacker, Application Architecter, KnowHow Dispenser and Bike Rider

Publication

Category

Recent Post

2016. 12. 20. 20:54 Angular/Concept

오늘은 Progressive Web Apps 개발에 대한 세미나 참석 내용을 정리해 본다. 



AMP

Progressive는 구글이 생각하는 서비스에 대한 점진적인 개발 진행 방향을 이야기 한다. 즉, 기술아니라 사용자 경험을 더 좋게 하기 위한 개념이다. AMP (Accelerated Mobile Pages) 는 모바일 페이지를 빠르게 만드는게 목표이다. 네트워크가 빠르면 모바일 웹이 느리다는 것을 느낄 수 없지만 느리면 반응이 느려진다. 해당 기술은 데스크톱에도 동일하게 적용될 수 있다. AMP는 정적 페이지를 위한 것이다. 


- amp html


<html amp>를 넣는다. <style amp-boilerplate>를 넣어 페이지 로딩바가 보이도록 한다. 

<!doctype html>

<html amp>

 <head>

   <meta charset="utf-8">

   <link rel="canonical" href="hello-world.html">

   <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">

   <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>

   <style amp-custom>

    

   </style>

   <script async src="https://cdn.ampproject.org/v0.js"></script>

 </head>

 <body>Hello World!</body>

</html>


- <link rel="canonical" href="amp.html">  amp를 지원하지 않는 브라우저대응을 위한 대신할 html 지정 

- 속도를 위해 amp로 된 웹페이지를 하나 더 만들어 서비스 하는것이다. amp는 기존의 html, css를 변경해서 적용하는 것이다. 



Service Worker

Web Worker는 메인페이지와 병렬 스크립트를 실행하는 백그라운드 워커를 생성하는 API로서 메세지 전송기반의 스레드 수행과 유사하다. UI Rendering과 분리되어 수행할 수 있다. 따라서 Web Work에서는 


- DOM을 직접 건드릴 수 없다. 

- 자체적인 글로벌 스코프

- 일부 속성과 API만 허가: 보면서 디버깅할 수 있는 것이 없다


Service Worker는 오프라인일 경우에도 웹 어플리케이션의 기동을 가능토록 하는 훅(Hook)을 포함하여, 어플리케이션으로 하여금 지속적인 백그라운드 포로세싱의 장점을 취하도록 하는 방법. 브라우저에서 로컬 웹서버가 있는 것과 같다. 


- 지속적인 백그라운드 처리

- 브라우저에 무언가 설치하는 것이다


정적인 파일에 대한 요청이 있을 때 네트워크가 끊어졌을 때 로컬 브라우저에서 서비스를 할 수 있게 한다. 백그라운드에서 정적 파일을 가져와서 브라우저 요청을 로컬 Service Worker 에서 처리해 준다. Application Cache의 스펙 오류를 해결하기 위해 Service Worker가 나왔다. 


- 기본 https 에서만 작동한다. 해킹방지: 중간 공격자를 피하기 위함

- 대신 127.0.0.1, localhost 테스트는 가능하다 


예, 오프라인 웹앱, 구글의 공룡게임 - 브라우저에 함께 존재한다. 


배워야 할 것은 


- 리소스 저장을 위한 Cache Storage - promise객체를 반환 

- 이벤트 생명 연장의 꿈: .waitUntile()  이벤트가 종료되지 않도록 한다  

- 패치 onfetch() 브라우저에서 리소스 접근 요청될 때 호출되는 이벤트 -> FetchEvent 요청내용을 담고 있다. .responseWith() 통해 응답한다



NAMP-CARD 

https://ampbyexample.com 좀 더 심화된 예제 사이트 이다. sw.js를 작성한다. 


var CACHE_NAME = 'pwa-workshop.github.id-namp-card-cache-v1';

// 하기 해당하는 내용을 캐쉬에 저장한다 

var urlsToCache = [

'/namp-card',

    '/index.html',

    '/manifest.json',

    '/user.png'

];


self.addEventListener('install', function(event) {

event.waitUntil(

caches.open(CACHE_NAME).then(function(cache) {

console.log(`Opened cache for namp-card ${new Date()}`);

return cache.addAll(urlsToCache);

})

);

});


self.addEventListener('fetch', function(event) {

    event.waitUntile(

        // 캐쉬안에 브라우저 요청과 매칭되는 것이 있으면 리턴을 해준다. 

        // 없으면 fetch(event, request.url)로 원격 서버에 요청 

        caches

            .match(event.request.url)

            .then(function(res) {

                return res || fetch(event, request.url);

            })

    )

});


등록을 한다. amp-install-serviceworker 스크립트를 이용하면 하기 내용이 들어간다. 개발자가 직접 넣을 수 없다. 

navigator.serviceWorker.register('/sw.js', { scope: '/' })

          .then(function(registration) {

                console.log('Service Worker Registered');

          });


https://airhorner.com/ 예의 DevTool에서 Service Worker를 볼 수 있다. 




모바일 기기에 설치형 웹앱 만들기

설치형이란? 


- 네트워크 불안하거나 오프라인인 경우에도 동작

- 홈스크린에서 바로 실행

- 앱의 이름과 아이콘을 제공


동작 가능한 웹앱


- 서비스워커의 지원 필요

- 프리캐쉬(Pre-cache)된 애플리케이션 프레임워크(App-shell) 사용

- 서비스워커를 통해 Indexed DB 또는 히스토리컬 데이터 디스플레이 


반드시 웹 메니페이스(Manifest)를 작성해야 함


- 설치 방법을 기술: 브라우저에서 Add to Home Screen 하면 모바일 바탕화면에 아이콘이 나온다. -> 굳이 앱을 설치하지 않아도 접근 가능토록 한다

- Splash 윈도우 사용가능: 아이콘 지정, 텍스트 지정 

- Prompt (부추기기)를 통해 Add to Home Screen를 하도록 유도한다. 이를 통해 앱의 설치없이 전환율을 높인다. 

- 노드 모듈의 pwa-manifest를 설치해서 사용할 수도 있다. 



실제로 수행하는 순서 참조


-  https://github.com/pwa-workshop/roadshow/blob/master/turn-into-an-installable-webapp.md

- github.com의 개인 프로필로에서 https 를 사용토록 한다.  



<참조> 

https://github.com/pwa-workshop/namp-card

https://www.ampproject.org/ko

posted by 윤영식