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/045a5f54b0ace4ff7c34c8703ae80afe to your computer and use it in GitHub Desktop.

Select an option

Save JuanVqz/045a5f54b0ace4ff7c34c8703ae80afe to your computer and use it in GitHub Desktop.
PWA en Rails - Demo 3: Cache Inteligente | RubySur 2026

PWA en Rails - Demo 3: Cache Inteligente

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

Estrategia mixta: Cache First para assets estaticos (CSS, JS, imagenes) y Network First para navegacion HTML con fallback a pagina offline.

Archivos

  • service-worker.jsapp/views/pwa/service-worker.js

Repo

// PWA en Rails - Demo 3 | 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: estrategia mixta
self.addEventListener("fetch", (event) => {
const url = new URL(event.request.url)
// Assets estaticos: Cache First (instantaneo)
if (url.pathname.match(/\.(css|js|png|jpg|svg|woff2)$/)) {
event.respondWith(
caches.match(event.request).then((cached) => {
if (cached) return cached
return fetch(event.request).then((response) => {
const clone = response.clone()
caches.open(CACHE_NAME)
.then((cache) => cache.put(event.request, clone))
return response
})
})
)
return
}
// Navegacion HTML: Network First con fallback offline
if (event.request.mode === "navigate") {
event.respondWith(
fetch(event.request)
.catch(() => caches.match("/offline.html"))
)
return
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment