Introdução a PWA

Thiago Dallacqua

Software Engineer

Murcul

 

Frontend developer

Genscape

O que significa PWA

Progressive Web Apps são aplicações que além de funcionarem como uma aplicação comum têm "super poderes" como a capacidade de rodar offline, conterem push notification, ter comportamento similar ao de aplicações nativas e muito mais

Peças fundamentais

  • Service Worker
  • manifest.json

manifest.json

Tem a finalidade de especificar metadados básicos para funcionamento/look and feel da aplicação quando rodar em dispositivos mobile após ser "instalada".

{
  "short_name": "API Frontend",
  "name": "Node API Frontend",
  "icons": [
    {
      "src": "favicon.ico",
      "sizes": "64x64 32x32 24x24 16x16",
      "type": "image/x-icon"
    }
  ],
  "start_url": "./index.html",
  "display": "standalone",
  "theme_color": "#000000",
  "background_color": "#ffffff"
}

https://developers.google.com/web/fundamentals/web-app-manifest/

Service Worker

  • É o coração da PWA
  • Responsável por todas as funcionalidades
  • Tem vários "listeners" para diversos eventos
  • Corre em uma thread separada da aplicação em sí

Service Worker

if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('/sw.js').then(function(registration) {
      // Registration was successful
      console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }).catch(function(err) {
      // registration failed :(
      console.log('ServiceWorker registration failed: ', err);
    });
  });
}

const CACHE_NAME = 'my-site-cache-v1';
const urlsToCache = [
  '/',
  '/styles/main.css',
  '/script/main.js'
];

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

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        // Cache hit - return response
        if (response) {
          return response;
        }
        return fetch(event.request);
      }
    )
  );
});

Service Worker

Prerequisitos para o Service Worker

  • HTTPS é obrigatório
  • Deve ter suporte in-browser

https://jakearchibald.github.io/isserviceworkerready/

Acessem o repositório

  • https://github.com/ThiagoDallacqua/pwa-workshop
Made with Slides.com