Skip to content

Instantly share code, notes, and snippets.

@JuanVqz
Last active April 13, 2026 19:19
Show Gist options
  • Select an option

  • Save JuanVqz/b434e873f73298024cd25223cee8a1be to your computer and use it in GitHub Desktop.

Select an option

Save JuanVqz/b434e873f73298024cd25223cee8a1be to your computer and use it in GitHub Desktop.
PWA en Rails - Demo 2: Service Worker Basico | RubySur 2026

PWA en Rails - Demo 2: Service Worker Basico

Charla "PWA en Rails" - RubySur - 13 de abril de 2026 Video: https://www.youtube.com/watch?v=ppxalpIKpGg

Agrega un service worker que pre-cachea una pagina offline. Cuando el usuario pierde la red, ve tu pagina en vez del dinosaurio de Chrome.

Archivos

  • service-worker.jsapp/views/pwa/service-worker.js
  • offline.htmlpublic/offline.html
  • _head.html.erb → agregar el script de registro del SW en el <head>

Repo

<%# app/views/layouts/_head.html.erb — agregar al final del <head>: %>
<script>
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/service-worker")
}
</script>
<!DOCTYPE html>
<html>
<head>
<title>Sin conexion - May Store</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
font-family: system-ui, sans-serif;
display: flex; align-items: center; justify-content: center;
min-height: 100vh; margin: 0;
background: #f3f4f6; color: #1f2937;
text-align: center;
}
h1 { font-size: 1.5rem; margin-bottom: 0.5rem; }
p { color: #6b7280; }
button {
margin-top: 1rem; padding: 0.5rem 1.5rem;
background: red; color: white; border: none;
border-radius: 0.375rem; cursor: pointer; font-size: 1rem;
}
</style>
</head>
<body>
<div>
<h1>Sin conexion</h1>
<p>No se pudo conectar al servidor.</p>
<button onclick="location.reload()">Reintentar</button>
</div>
</body>
</html>
// PWA en Rails - Demo 2 | RubySur - 13/04/2026
// app/views/pwa/service-worker.js
const CACHE_NAME = "may-store-v1"
// 1. Install: pre-cachear la pagina offline
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME)
.then((cache) => cache.addAll(["/offline.html"]))
)
self.skipWaiting()
})
// 2. Activate: limpiar caches viejos
self.addEventListener("activate", (event) => {
event.waitUntil(
caches.keys().then((names) =>
Promise.all(
names.filter((n) => n !== CACHE_NAME)
.map((n) => caches.delete(n))
)
)
)
self.clients.claim()
})
// 3. Fetch: si falla una navegacion, mostrar offline.html
self.addEventListener("fetch", (event) => {
if (event.request.mode === "navigate") {
event.respondWith(
fetch(event.request)
.catch(() => caches.match("/offline.html"))
)
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment