Spaces:
Paused
Paused
perf: HTML stale-while-revalidate + 재생 중 reload 보류
Browse filesSW HTML 핸들러를 network-first → SWR로. 재방문 시 캐시된 HTML
즉시 반환 → 부팅 시작 ~0초. 백그라운드 fetch 후 본문 hash가
다르면 클라이언트에 sw-updated 알림 → 자동 reload로 새 코드 반영.
- FNV-1a 32bit로 응답 본문 hash 계산, X-Tvchak-Body-Hash 헤더로
캐시에 저장. 다음 비교 때 이 헤더 키로 변경 감지.
- 클라이언트 자동 reload는 영상 재생 중이면 보류. pause/visibility
hidden 시 다시 시도. 시청 끊김 방지.
- CACHE 버전 v7 → v8로 옛 SW 강제 무효화.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- index.html +25 -10
- sw.js +63 -10
index.html
CHANGED
|
@@ -3773,20 +3773,35 @@ function setupPWA() {
|
|
| 3773 |
setInterval(() => reg.update().catch(() => {}), 60 * 60 * 1000);
|
| 3774 |
})
|
| 3775 |
.catch((e) => console.warn('SW reg failed:', e));
|
| 3776 |
-
// 새 SW가 활성화되면 자동 reload (한 번만)
|
|
|
|
| 3777 |
let _reloading = false;
|
| 3778 |
-
|
| 3779 |
-
|
| 3780 |
-
_reloading = true;
|
| 3781 |
-
console.log('[sw] new version activated — reloading');
|
| 3782 |
-
setTimeout(() => location.reload(), 200);
|
| 3783 |
-
}
|
| 3784 |
-
});
|
| 3785 |
-
// controllerchange도 reload (다른 탭에서 update 트리거되었을 때)
|
| 3786 |
-
navigator.serviceWorker.addEventListener('controllerchange', () => {
|
| 3787 |
if (_reloading) return;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3788 |
_reloading = true;
|
|
|
|
| 3789 |
setTimeout(() => location.reload(), 200);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3790 |
});
|
| 3791 |
}
|
| 3792 |
|
|
|
|
| 3773 |
setInterval(() => reg.update().catch(() => {}), 60 * 60 * 1000);
|
| 3774 |
})
|
| 3775 |
.catch((e) => console.warn('SW reg failed:', e));
|
| 3776 |
+
// 새 SW가 활성화되면 자동 reload (한 번만).
|
| 3777 |
+
// 단 영상 재생 중이면 보류 — 사용자가 일시정지하거나 다음 탭 전환 시 갱신.
|
| 3778 |
let _reloading = false;
|
| 3779 |
+
let _pendingReload = false;
|
| 3780 |
+
const tryReload = (reason) => {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3781 |
if (_reloading) return;
|
| 3782 |
+
const v = document.getElementById('player');
|
| 3783 |
+
const playing = v && !v.paused && !v.ended && v.currentTime > 0;
|
| 3784 |
+
if (playing) {
|
| 3785 |
+
_pendingReload = true;
|
| 3786 |
+
console.log(`[sw] ${reason} — defer reload (playing)`);
|
| 3787 |
+
return;
|
| 3788 |
+
}
|
| 3789 |
_reloading = true;
|
| 3790 |
+
console.log(`[sw] ${reason} — reloading`);
|
| 3791 |
setTimeout(() => location.reload(), 200);
|
| 3792 |
+
};
|
| 3793 |
+
navigator.serviceWorker.addEventListener('message', (e) => {
|
| 3794 |
+
if (e.data?.type === 'sw-updated') tryReload('new version activated');
|
| 3795 |
+
});
|
| 3796 |
+
// controllerchange도 reload (다른 탭에서 update 트리거되었을 때)
|
| 3797 |
+
navigator.serviceWorker.addEventListener('controllerchange', () => tryReload('controllerchange'));
|
| 3798 |
+
// 영상이 일시정지/종료될 때 보류된 reload 재시도
|
| 3799 |
+
document.addEventListener('pause', (e) => {
|
| 3800 |
+
if (_pendingReload && e.target?.id === 'player') tryReload('pending after pause');
|
| 3801 |
+
}, true);
|
| 3802 |
+
// 탭이 hidden으로 갈 때도 기회 — 사용자가 다른 작업 중이라 안 보임
|
| 3803 |
+
document.addEventListener('visibilitychange', () => {
|
| 3804 |
+
if (_pendingReload && document.visibilityState === 'hidden') tryReload('pending on hidden');
|
| 3805 |
});
|
| 3806 |
}
|
| 3807 |
|
sw.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
| 1 |
-
// 정적 자원
|
| 2 |
-
// index.html
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
self.addEventListener('install', (e) => {
|
| 6 |
// 새 SW는 즉시 활성화 (옛 SW 대기 안 함)
|
|
@@ -20,23 +23,73 @@ self.addEventListener('activate', (e) => {
|
|
| 20 |
})());
|
| 21 |
});
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
self.addEventListener('fetch', (e) => {
|
| 24 |
const url = new URL(e.request.url);
|
| 25 |
if (e.request.method !== 'GET') return;
|
| 26 |
// API / cdn / 외부 호스트는 캐시 우회 (항상 네트워크)
|
| 27 |
if (url.pathname.startsWith('/api/') || url.pathname.startsWith('/cdn') || url.origin !== self.location.origin) return;
|
| 28 |
|
| 29 |
-
// HTML(/, /index.html)
|
| 30 |
if (url.pathname === '/' || url.pathname === '/index.html') {
|
| 31 |
-
e.respondWith(
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
if (resp && resp.status === 200) {
|
| 34 |
-
|
| 35 |
-
caches.open(CACHE).then(c => c.put(e.request, clone)).catch(() => {});
|
| 36 |
}
|
| 37 |
return resp;
|
| 38 |
-
}
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
| 40 |
return;
|
| 41 |
}
|
| 42 |
|
|
|
|
| 1 |
+
// 정적 자원 캐시 전략:
|
| 2 |
+
// - index.html: stale-while-revalidate. 캐시 즉시 반환 → 부팅 0초 시작.
|
| 3 |
+
// 백그라운드로 새 HTML fetch 후 응답이 캐시와 다르면 클라이언트에 sw-updated 알림 → 자동 reload.
|
| 4 |
+
// - 그 외 정적(favicon, manifest, sw.js 자체 제외): cache-first.
|
| 5 |
+
// - API / cdn / 외부 호스트: 항상 네트워크 (캐시 우회).
|
| 6 |
+
const CACHE = 'tvchak-v8';
|
| 7 |
|
| 8 |
self.addEventListener('install', (e) => {
|
| 9 |
// 새 SW는 즉시 활성화 (옛 SW 대기 안 함)
|
|
|
|
| 23 |
})());
|
| 24 |
});
|
| 25 |
|
| 26 |
+
// 본문 변경 감지용 — Cache API의 ResponseBody는 한 번만 읽으므로 미리 hash 계산해 저장.
|
| 27 |
+
// 가벼운 FNV-1a 32bit (HTML 50KB 대상이라 충분).
|
| 28 |
+
async function hashOfResponse(resp) {
|
| 29 |
+
try {
|
| 30 |
+
const text = await resp.clone().text();
|
| 31 |
+
let h = 0x811c9dc5;
|
| 32 |
+
for (let i = 0; i < text.length; i++) {
|
| 33 |
+
h ^= text.charCodeAt(i);
|
| 34 |
+
h = (h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24))) >>> 0;
|
| 35 |
+
}
|
| 36 |
+
return h.toString(16);
|
| 37 |
+
} catch { return null; }
|
| 38 |
+
}
|
| 39 |
+
// 캐시 항목에 우리만 쓰는 해시 헤더를 붙여 저장. 다음 비교 때 이 헤더를 키로.
|
| 40 |
+
async function storeWithHash(cache, request, resp) {
|
| 41 |
+
const hash = await hashOfResponse(resp);
|
| 42 |
+
if (hash == null) { await cache.put(request, resp); return; }
|
| 43 |
+
const text = await resp.clone().text();
|
| 44 |
+
const newHeaders = new Headers(resp.headers);
|
| 45 |
+
newHeaders.set('X-Tvchak-Body-Hash', hash);
|
| 46 |
+
await cache.put(request, new Response(text, {
|
| 47 |
+
status: resp.status,
|
| 48 |
+
statusText: resp.statusText,
|
| 49 |
+
headers: newHeaders,
|
| 50 |
+
}));
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
self.addEventListener('fetch', (e) => {
|
| 54 |
const url = new URL(e.request.url);
|
| 55 |
if (e.request.method !== 'GET') return;
|
| 56 |
// API / cdn / 외부 호스트는 캐시 우회 (항상 네트워크)
|
| 57 |
if (url.pathname.startsWith('/api/') || url.pathname.startsWith('/cdn') || url.origin !== self.location.origin) return;
|
| 58 |
|
| 59 |
+
// HTML(/, /index.html) — stale-while-revalidate
|
| 60 |
if (url.pathname === '/' || url.pathname === '/index.html') {
|
| 61 |
+
e.respondWith((async () => {
|
| 62 |
+
const cache = await caches.open(CACHE);
|
| 63 |
+
const cached = await cache.match(e.request);
|
| 64 |
+
// 백그라운드로 네트워크 갱신 (await 안 함 — 캐시는 바로 반환)
|
| 65 |
+
const networkPromise = fetch(e.request).then(async (resp) => {
|
| 66 |
+
if (!resp || resp.status !== 200) return;
|
| 67 |
+
const oldHash = cached?.headers.get('X-Tvchak-Body-Hash');
|
| 68 |
+
const newHash = await hashOfResponse(resp);
|
| 69 |
+
await storeWithHash(cache, e.request, resp);
|
| 70 |
+
// 본문이 달라졌으면 클라이언트에 알림 — 자동 reload 트리거
|
| 71 |
+
if (cached && oldHash && newHash && oldHash !== newHash) {
|
| 72 |
+
const clients = await self.clients.matchAll({ type: 'window' });
|
| 73 |
+
for (const c of clients) c.postMessage({ type: 'sw-updated' });
|
| 74 |
+
}
|
| 75 |
+
}).catch(() => {});
|
| 76 |
+
if (cached) {
|
| 77 |
+
// 캐시 있으면 즉시 반환, 네트워크는 백그라운드
|
| 78 |
+
e.waitUntil(networkPromise);
|
| 79 |
+
return cached;
|
| 80 |
+
}
|
| 81 |
+
// 캐시 없으면(첫 방문) 네트워크 결과 기다림
|
| 82 |
+
try {
|
| 83 |
+
const resp = await fetch(e.request);
|
| 84 |
if (resp && resp.status === 200) {
|
| 85 |
+
await storeWithHash(cache, e.request, resp.clone());
|
|
|
|
| 86 |
}
|
| 87 |
return resp;
|
| 88 |
+
} catch {
|
| 89 |
+
// 오프라인 + 캐시 없음 — 최후 폴백
|
| 90 |
+
return cache.match('/index.html') || new Response('offline', { status: 503 });
|
| 91 |
+
}
|
| 92 |
+
})());
|
| 93 |
return;
|
| 94 |
}
|
| 95 |
|