Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
Web to PWA!
Search
Sponsored
·
Ship Features Fearlessly
Turn features on and off without deploys. Used by thousands of Ruby developers.
→
Gefy Marcos
November 17, 2018
Technology
94
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Web to PWA!
Como transformar um site em uma PWA nota 100 no lighthouse!
Gefy Marcos
November 17, 2018
Transcript
64 slides
Web to
None
None
None
Site estático Site dinâmico Ajax Site Responsivo PWA 1991 2005
1997 2012 2015
Quem está usando?
O que é PWA?
"Progressive Web Apps são experiências que combinam o melhor da
web e o melhor dos aplicativos.” Fonte: Developers Google
Pré-requisitos
Progressivo
Responsivo
Independente de conectividade
Semelhante a aplicativos
Atual
Seguro
Descobrível
Reenvolvente
Instalável
None
Linkável
Lighthouse
https, sempre HTTPS 1
O que fazer? • Habilitar HTTPS no servidor, isso é
obrigatório. • Redirecionar o status 301 também para HTTPS.
Como fazer?
responsivo e rápido 2
Como fazer? • Media queries. • Sempre se preocupar com
performance e boas práticas. • Lighthouse.
Como fazer? <meta name="viewport" content="width=device-width, initial-scale=1” > • Sempre definir
corretamente o viewport no browser.
Cor tema do site 3
None
Como fazer? <meta name="theme-color" content="#000000"> • Escolher uma cor e
buscar o código hexadecimal.
Manifesto 4
O que fazer? • Criar o manifest.json. • App Manifesto
ou PWA Builder.
{ "name": "Gefy Marcos", "short_name": "Gefy", "theme_color": "#333333", "background_color": "#000000",
"display": “standalone", "//fullscreen, browser “start_url": "https:"//gefy.com.br/index.html", "orientation": “portrait", "//any, landscape "icons": [{ "src": "/img/logo-512x512.png", "sizes": "512x512", "type": "image/png" }] }
Importante "short_name": "Gefy", • O short_name não pode ter mais
que 12 letras. • Nome que aparece com o ícone no celular.
Importante • O background_color é obrigatório. "background_color": "#000000",
Importante • É obrigatório ao menos um ícone 512x512. •
Icone somente PNG. "icons": [{ "src": "/img/logo-512x512.png", "sizes": "512x512", "type": "image/png" }]
Importante <link rel="manifest" href="/manifest.json"> • Adicionar no head.
Service Worker 5
Fonte: https://caniuse.com/#feat=serviceworkers Suporte
É um script executado em segundo plano pelo navegador.
Executado separado da página web.
Possibilita utilizar push notifications, sincronização em segundo plano, etc…
Capacidade de interceptar e tratar solicitações de rede.
O service worker funciona numa thread separada do browser, ele
não tem acesso ao DOM. Importante
Sempre deve ter o mesmo nome e ficar no mesmo
local para não gerar duplicação. Importante
Lembre-se de deletar o cache antigo quando o site for
atualizado. Importante
Como fazer? • Registrar o service worker no nosso head.
Como fazer? if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js') .then(function(registration) {
console.log('Registration successful’); }).catch(function(err) { console.log('Registration failed: '); }); }
Ciclo de vida
Install É ativado só uma vez, ao registrar o sw.js.
var filesToAdd = ['/'] self.addEventListener('install', function(event) { event.waitUntil( caches.open('gefy-pwa') .then(function(cache)
{ return cache.addAll(filesToAdd); }) ); });
É ativado uma vez, após o “install”, após o service
worker assumir o controle dos caches. Activate
self.addEventListener('activate', function(event) { var cacheWhitelist = ['gefy-pwa']; event.waitUntil( caches.keys().then(function(cacheNames) {
return Promise.all( cacheNames.map(function(cacheName) { if (cacheWhitelist .indexOf(cacheName) ""=== -1) { return caches.delete(cacheName); } }) ); }) ); });
É ativado toda vez que uma página é requisitada. Fetch
self.addEventListener('fetch', function(event) { event.respondWith( checkResponse(event.request) .catch(function() { return returnFromCache(event.request)} ));
event.waitUntil(addToCache(event.request)); });
var checkResponse = function(request) { return new Promise(function(fulfill, reject) {
fetch(request) .then(function(response) { if(response.status ""!== 404) { fulfill(response) } else { reject() } }, reject) }); };
var returnFromCache = function(request) { return caches.open('gefy-pwa') .then(function (cache) {
return cache.match(request) .then(function (matching) { if(!matching "|| matching.status "== 404) { return cache.match(‘/404.html') } else { return matching } }); }); };
var addToCache = function(request) { return caches.open('gefy-pwa') .then(function (cache) {
return fetch(request) .then(function (response) { return cache.put(request, response); }); }); };
Agora temos nosso primeiro PWA! YES…
• Online first • Offline first Abordagens
self.addEventListener('fetch', function(event) { event.respondWith( returnFromCache(event.request) .catch(function() { return checkResponse(event.request)} ));
event.waitUntil(addToCache(event.request)); });
Testando
• O que é e como funciona um PWA. •
Princípios básicos. • Como testar um PWA. • Cor de tema. • Manifesto. • Service worker. • Cache e redirecionamento. Conclusão
Obrigado! @gefymarcos gefy.com.br/talks
More Decks by Gefy Marcos
See All by Gefy Marcos
Desbravando a Carreira em Desenvolvimento: Dicas e Estratégias para iniciantes
gefymarcos
0
58
Zod: Levando a validação de dados a um novo nível.
gefymarcos
0
1.6k
ReactJS Starter
gefymarcos
0
52
Clean Code: Boas práticas e design de código
gefymarcos
0
180
React Native por onde começar
gefymarcos
0
170
Other Decks in Technology
See All in Technology
Platform Engineering をベースとした Agentic Software Factory の実践
110y
3
1k
データから見る AI時代のエンジニア転職と採用
junya_okura
4
1.4k
実測データからサービスの成長余力を測る。負荷シナリオ・テストデータ・限界値の設計
kazatohiei
1
190
フロントエンドのテストカバレッジは 100%強制がいい
bengo4com
7
3.9k
競馬予想をAIでやってみた話
yoshimura_datam
0
150
専門家に使ってもらうAIプロダクトをつくる - 病院の医事課向けDPCコーディング支援システムの設計と評価
hagino3000
4
1.1k
AWS re:Invent 2026 FSI Pre-Event Networking Night
junjikoide
0
330
Well, that’s weird…
csswizardry
3
250
技術同人誌を作る方法
yoshimura_datam
0
110
AIが学べる子供の夏休みの自由研究教材を作ったが空振りだった話
yoshimura_datam
0
110
AWS Well-Arhitected Frameworkセキュリティの柱 について
miu_crescent
PRO
2
270
AWS DevOps Agentの構造から読み解く運用 AI エージェントの設計原則/aws-devops-agent-design-principles
tomoki10
0
310
Featured
See All Featured
Fantastic passwords and where to find them - at NoRuKo
philnash
53
4k
Digital Ethics as a Driver of Design Innovation
axbom
PRO
2
570
The Power of CSS Pseudo Elements
geoffreycrofte
82
6.7k
sira's awesome portfolio website redesign presentation
elsirapls
0
530
So, you think you're a good person
axbom
PRO
2
2.3k
ReactJS: Keep Simple. Everything can be a component!
pedronauck
666
130k
More Than Pixels: Becoming A User Experience Designer
marktimemedia
3
640
The AI Revolution Will Not Be Monopolized: How open-source beats economies of scale, even for LLMs
inesmontani
PRO
3
3.8k
Primal Persuasion: How to Engage the Brain for Learning That Lasts
tmiket
0
530
Navigating the Design Leadership Dip - Product Design Week Design Leaders+ Conference 2024
apolaine
2
530
Designing for humans not robots
tammielis
254
26k
The Curious Case for Waylosing
cassininazir
1
630