perf: arranque ultrarapido pwa con gzip compression stale-while-revalidate y renderizado optimista
This commit is contained in:
+6
-5
@@ -11,7 +11,8 @@
|
||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
||||
<meta name="apple-mobile-web-app-title" content="SiboPay">
|
||||
<meta name="mobile-web-app-capable" content="yes">
|
||||
<link rel="preload" href="/css/styles.css?v=14.0" as="style">
|
||||
<link rel="preload" href="/js/app.js?v=14.0" as="script">
|
||||
<link rel="stylesheet" href="/css/styles.css?v=14.0">
|
||||
<link rel="stylesheet" href="/css/desktop.css?v=2.2">
|
||||
<style>
|
||||
@@ -3896,9 +3897,9 @@
|
||||
</nav>
|
||||
|
||||
<script src="/js/dialogs.js?v=13.8"></script>
|
||||
<script src="/js/sounds.js?v=13.8"></script>
|
||||
<script src="/js/jsQR.js"></script>
|
||||
<script src="/js/food-icons.js?v=1.1"></script>
|
||||
<script src="/js/app.js?v=14.0"></script>
|
||||
<script src="/js/sounds.js?v=13.8" defer></script>
|
||||
<script src="/js/jsQR.js" defer></script>
|
||||
<script src="/js/food-icons.js?v=1.1" defer></script>
|
||||
<script src="/js/app.js?v=15.0"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+59
-28
@@ -68,7 +68,7 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||
|
||||
// Registrar Service Worker para PWA
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker.register('/sw.js?v=15.0').then(reg => {
|
||||
navigator.serviceWorker.register('/sw.js?v=16.0').then(reg => {
|
||||
reg.update().catch(() => {});
|
||||
if ('Notification' in window && Notification.permission === 'granted') {
|
||||
subscribeDeviceToWebPush().catch(() => {});
|
||||
@@ -545,13 +545,39 @@ async function applyUserRoleSession() {
|
||||
|
||||
const btnPadres = document.getElementById('btnModePadres');
|
||||
if (btnPadres) btnPadres.style.display = 'none';
|
||||
|
||||
await loadInitialData();
|
||||
|
||||
// 🚀 RENDERIZADO OPTIMISTA INSTANTÁNEO (0 ms):
|
||||
// El estudiante ve su carné, saldo y botón de QR de inmediato con sus datos guardados localmente
|
||||
if (currentUser.estudiante) {
|
||||
await selectStudent(currentUser.estudiante.id);
|
||||
currentStudent = currentUser.estudiante;
|
||||
currentAppMode = 'teens';
|
||||
updateStudentUI();
|
||||
}
|
||||
|
||||
// En segundo plano y en paralelo: sincronizar datos frescos sin congelar la pantalla
|
||||
const studentTasks = [loadInitialData(true)];
|
||||
|
||||
if (currentUser.estudiante) {
|
||||
studentTasks.push(
|
||||
fetch(`/api/estudiantes/${currentUser.estudiante.id}`)
|
||||
.then(r => r.json())
|
||||
.then(freshStudent => {
|
||||
if (freshStudent && freshStudent.id) {
|
||||
currentStudent = freshStudent;
|
||||
currentUser.estudiante = freshStudent;
|
||||
try {
|
||||
localStorage.setItem('sibopay_user', JSON.stringify(currentUser));
|
||||
} catch (_) {}
|
||||
updateStudentUI();
|
||||
}
|
||||
})
|
||||
.catch(e => console.warn('Error sincronizando estudiante:', e))
|
||||
);
|
||||
} else if (students.length > 0) {
|
||||
selectStudent(students[0].id);
|
||||
}
|
||||
|
||||
await Promise.allSettled(studentTasks);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -678,34 +704,39 @@ function pwaNavigateTo(target) {
|
||||
}
|
||||
}
|
||||
|
||||
async function loadInitialData() {
|
||||
async function loadInitialData(isStudent = false) {
|
||||
try {
|
||||
// 1. Cargar estudiantes
|
||||
const resEst = await fetch('/api/estudiantes');
|
||||
students = await resEst.json();
|
||||
|
||||
populateStudentSelector();
|
||||
|
||||
// 2. Cargar productos y categorías de la escuela activa
|
||||
const escId = (currentUser && currentUser.escuela_id) || (currentStudent && currentStudent.escuela_id) || 1;
|
||||
const resProd = await fetch(`/api/productos?escuela_id=${escId}`);
|
||||
const dataProd = await resProd.json();
|
||||
categories = dataProd.categorias || [];
|
||||
|
||||
// Deduplicar productos para garantizar que nunca se repita ninguno
|
||||
const seenNames = new Set();
|
||||
products = (dataProd.productos || []).filter(p => {
|
||||
const key = String(p.nombre).trim().toLowerCase();
|
||||
if (seenNames.has(key)) return false;
|
||||
seenNames.add(key);
|
||||
return true;
|
||||
});
|
||||
|
||||
renderCategories();
|
||||
renderProducts();
|
||||
// 🚀 Ejecución paralela ultra rápida con Promise.all
|
||||
const promises = [
|
||||
fetch(`/api/productos?escuela_id=${escId}`).then(r => r.json()).catch(() => ({ categorias: [], productos: [] })),
|
||||
loadCardDesigns()
|
||||
];
|
||||
|
||||
// 3. Cargar catálogo de diseños de tarjetas
|
||||
await loadCardDesigns();
|
||||
if (!isStudent) {
|
||||
promises.push(fetch('/api/estudiantes').then(r => r.json()).catch(() => []));
|
||||
}
|
||||
|
||||
const [dataProd, _, resEst] = await Promise.all(promises);
|
||||
|
||||
if (dataProd) {
|
||||
categories = dataProd.categorias || [];
|
||||
const seenNames = new Set();
|
||||
products = (dataProd.productos || []).filter(p => {
|
||||
const key = String(p.nombre).trim().toLowerCase();
|
||||
if (seenNames.has(key)) return false;
|
||||
seenNames.add(key);
|
||||
return true;
|
||||
});
|
||||
renderCategories();
|
||||
renderProducts();
|
||||
}
|
||||
|
||||
if (!isStudent && Array.isArray(resEst)) {
|
||||
students = resEst;
|
||||
populateStudentSelector();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error cargando datos iniciales:', error);
|
||||
}
|
||||
|
||||
+33
-24
@@ -1,5 +1,5 @@
|
||||
// SiboPay PWA Service Worker v15.0 - Dashboard Ejecutivo de Padres & Persistencia Sesión F5
|
||||
const CACHE_NAME = 'sibopay-v15.0';
|
||||
// SiboPay PWA Service Worker v16.0 - Ultra Fast Startup & Stale-While-Revalidate
|
||||
const CACHE_NAME = 'sibopay-v16.0';
|
||||
const STATIC_ASSETS = [
|
||||
'/',
|
||||
'/index.html',
|
||||
@@ -7,13 +7,13 @@ const STATIC_ASSETS = [
|
||||
'/pistola.html',
|
||||
'/carnet.html',
|
||||
'/manifest.json',
|
||||
'/css/styles.css',
|
||||
'/css/desktop.css',
|
||||
'/js/dialogs.js',
|
||||
'/js/app.js',
|
||||
'/css/styles.css?v=14.0',
|
||||
'/css/desktop.css?v=2.2',
|
||||
'/js/dialogs.js?v=13.8',
|
||||
'/js/app.js?v=14.0',
|
||||
'/js/pos.js',
|
||||
'/js/sounds.js',
|
||||
'/js/food-icons.js',
|
||||
'/js/sounds.js?v=13.8',
|
||||
'/js/food-icons.js?v=1.1',
|
||||
'/icons/icon-192.png',
|
||||
'/icons/icon-512.png',
|
||||
'/img/sibopay-emblem.png',
|
||||
@@ -46,11 +46,11 @@ self.addEventListener('activate', (event) => {
|
||||
);
|
||||
});
|
||||
|
||||
// Network-First con fallback a caché para navegación y recursos estáticos
|
||||
// Estrategia Stale-While-Revalidate para apertura instantánea (0ms) en móviles
|
||||
self.addEventListener('fetch', (event) => {
|
||||
const url = new URL(event.request.url);
|
||||
|
||||
// APIs y Server-Sent Events (SSE): Directo a red sin caché
|
||||
// APIs y Server-Sent Events (SSE): Directo a red en tiempo real sin caché
|
||||
if (url.pathname.startsWith('/api/') || url.pathname.startsWith('/events')) {
|
||||
return;
|
||||
}
|
||||
@@ -61,24 +61,33 @@ self.addEventListener('fetch', (event) => {
|
||||
}
|
||||
|
||||
event.respondWith(
|
||||
fetch(event.request)
|
||||
.then((networkResponse) => {
|
||||
if (networkResponse && networkResponse.status === 200) {
|
||||
const responseClone = networkResponse.clone();
|
||||
caches.open(CACHE_NAME).then((cache) => {
|
||||
cache.put(event.request, responseClone);
|
||||
});
|
||||
}
|
||||
return networkResponse;
|
||||
})
|
||||
.catch(() => {
|
||||
return caches.match(event.request).then((cachedResponse) => {
|
||||
if (cachedResponse) return cachedResponse;
|
||||
caches.match(event.request).then((cachedResponse) => {
|
||||
// Lanzar actualización en segundo plano (revalidate) sin bloquear la pantalla
|
||||
const fetchPromise = fetch(event.request)
|
||||
.then((networkResponse) => {
|
||||
if (networkResponse && networkResponse.status === 200) {
|
||||
const responseClone = networkResponse.clone();
|
||||
caches.open(CACHE_NAME).then((cache) => {
|
||||
cache.put(event.request, responseClone);
|
||||
});
|
||||
}
|
||||
return networkResponse;
|
||||
})
|
||||
.catch(() => {
|
||||
// Si no hay red y era navegación, retornar index.html en caché
|
||||
if (event.request.mode === 'navigate') {
|
||||
return caches.match('/index.html');
|
||||
}
|
||||
});
|
||||
})
|
||||
|
||||
// Si ya está en la memoria del teléfono, entregar INMEDIATAMENTE (<15ms)
|
||||
if (cachedResponse) {
|
||||
return cachedResponse;
|
||||
}
|
||||
|
||||
// Si es la primera vez que se descarga, esperar la respuesta de red
|
||||
return fetchPromise;
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user