페이지 3: 캐싱 전략 구현 및 Push 알림

3. 캐싱 전략 구현 및 Push 알림

가장 일반적인 캐싱 전략 중 하나인 Cache-first, Network-fallback을 구현하여 오프라인에서 콘텐츠를 제공합니다.

3.1. 캐싱 전략 구현 (fetch 이벤트)

fetch 이벤트 핸들러를 사용하여 요청을 가로채고, 캐시에서 먼저 찾은 후, 없으면 네트워크로 대체합니다.

self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request) // 1. 캐시에서 찾기
      .then((response) => {
        if (response) {
          return response; // 2. 캐시에 있으면 캐시 응답 반환
        }
        return fetch(event.request); // 3. 캐시에 없으면 네트워크 요청
      })
  );
});

3.2. 정적 자원 사전 캐싱 (install 이벤트)

앱 쉘(App Shell) 구조의 핵심 파일들을 Service Worker 설치 시점에 미리 캐시하여 즉각적인 로딩을 보장합니다.

const urlsToCache = [
  '/',
  '/index.html',
  '/styles.css',
  '/main.js'
];

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then((cache) => {
        console.log('Opened cache and pre-caching shell assets');
        return cache.addAll(urlsToCache);
      })
  );
});