PWA

Progressive WEB App?

Aplicativo da WEB Progressivo???

Progressivo?????????

A idéia é que sua página web se comporte como um APP nativo Progressivamente, não impedindo seu funcionamento como uma página web convencional

Metodologia de desenvolvimento de software

Pode ser visto como uma evolução híbrida entre as páginas da web regulares (ou sites) e um aplicativo móvel

Três Pilares

Confiável

Rápido

Envolvente

Poderes

Acessar o App sem internet

Instalar o App no dispositivo

Enviar notificações

Sincronizar dados em segundo plano

...

Exemplos

pokedex.org
essa própria apresentação

Como usar

Arquivo de Manifesto

Service Worker

Arquivo de Manifesto

					
            {
                "name": "HackerWeb",
                "short_name": "HackerWeb",
                "start_url": ".",
                "display": "standalone",
                "background_color": "#fff",
                "description": "A simply readable Hacker News app.",
                "icons": [
                    { 
                        "src": "images/touch/homescreen48.png",
                        "sizes": "48x48",
                        "type": "image/png"
                    }
                ]
            }
					
				

Arquivo de Manifesto

					
						
					
				

Service Worker

Register service worker


if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js')
    .then((reg) => {
      console.log('SW registered.', reg);
    });
}
    				

Vamos Praticar?

Fonte de estudos e exemplos

Google Developers - WEB Fundamentals

your-first-pwapp
offline-for-pwa

Criar Estrutura

index.html

styles/app.css

src/app.js

sw.js

index.html


          
          

Ola Mundo PWA

styles/app.css


          h1{
            color: silver;
          }
    		

src/app.js


          if ('serviceWorker' in navigator) {
            window.addEventListener('load', () => {
              navigator.serviceWorker.register('/sw.js').then(function (reg) {
                console.log('SW registration with scope: ', reg.scope);
              }, (err) => {
                console.log('ServiceWorker registration failed: ', err);
              });
            });
          } 
    		

eventos do service worker

install

fetch

activate

outros...

sw.js


          const CACHE_NAME = 'my-site-cache-v1';

          const urlsToCache = [
            '/',
            '/styles/app.css',
            '/src/app.js'
          ];
    		

sw.js event install


          self.addEventListener('install', function (event) {
            console.log('INSTALL', CACHE_NAME);
            event.waitUntil(
              caches.open(CACHE_NAME)
                .then(function (cache) {
                  return cache.addAll(urlsToCache);
                })
            );
          });
        
Cache API

sw.js event fetch


          self.addEventListener('fetch', function (event) {
            console.log('FETCH', CACHE_NAME);
            event.respondWith(
              caches.match(event.request)
                .then(function (response) {
                  if (response) {
                    return response;
                  }
                  return fetch(event.request);
                } 
                )
            );
          });
        

sw.js event activate


          self.addEventListener('activate', function (event) {
            console.log('ACTIVATE', CACHE_NAME);
            var cacheWhitelist = [CACHE_NAME];
            event.waitUntil(
              caches.keys().then(function (cacheNames) {
                return Promise.all(
                  cacheNames.map(function (cacheName) {
                    if (cacheWhitelist.indexOf(cacheName) === -1) {
                      return caches.delete(cacheName);
                    }
                  })
                );
              })
            );
          });
        

sw.js skipWaiting


          self.addEventListener('install', function (event) {
            console.log('INSTALL', CACHE_NAME);
            self.skipWaiting();
            event.waitUntil(
              caches.open(CACHE_NAME)
                .then(function (cache) {
                  return cache.addAll(urlsToCache);
                })
            );
          });
        

Reiniciar a Página quando tiver atualização


          if ('serviceWorker' in navigator) {
            window.addEventListener('load', () => {
              navigator.serviceWorker.register('/sw.js').then(function (reg) {
                console.log('SW registration with scope: ', reg.scope);
                reg.onupdatefound = () => {
                  const installingWorker = reg.installing;
                  installingWorker.onstatechange = () => {
                    if (installingWorker.state == 'installed' && navigator.serviceWorker.controller) {
                      window.location.reload();
                    }
                  };
                };
              }, (err) => {
                console.log('ServiceWorker registration failed: ', err);
              });
            });
          } 
        

Marcelo Michels

contato@marcelomichels.com

github.com/marcelo-michels