OfflineFirst 완벽 마스터
OfflineFirst의 핵심 개념과 실전 활용법
학습 항목
본 콘텐츠의 이미지 및 내용은 AI로 생성되었습니다.
이미지 로딩 중...
PWA Progressive Web App 최신기능
Progressive Web App의 최신 기능들을 실전 코드와 함께 배워봅니다. Service Worker, Push Notification, App Install 등 고급 PWA 기능을 다룹니다.
들어가며
이 글에서는 PWA Progressive Web App 최신기능에 대해 상세히 알아보겠습니다. 총 12가지 주요 개념을 다루며, 각각의 개념에 대한 설명과 실제 코드 예제를 함께 제공합니다.
목차
- Service_Worker_등록
- 오프라인_캐싱_전략
- Network_First_전략
- Push_Notification_구독
- Push_알림_수신
- App_설치_프롬프트
- Web_Manifest_설정
- Background_Sync
- Share_API_통합
- Badging_API
- Periodic_Background_Sync
- Cache_Storage_관리
1. Service Worker 등록
개요
Service Worker를 등록하여 PWA의 핵심 기능인 오프라인 지원과 백그라운드 동기화를 활성화합니다.
코드 예제
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(reg => console.log('SW registered:', reg))
.catch(err => console.error('SW error:', err));
}
설명
navigator.serviceWorker API를 통해 서비스 워커 파일을 등록하고, 등록 성공 시 콘솔에 결과를 출력합니다.
2. 오프라인 캐싱 전략
개요
Cache API를 활용하여 네트워크가 끊어져도 앱이 정상 작동하도록 리소스를 캐싱합니다.
코드 예제
self.addEventListener('install', event => {
event.waitUntil(
caches.open('v1').then(cache =>
cache.addAll(['/index.html', '/app.js', '/style.css'])
)
);
});
설명
Service Worker 설치 시 중요한 리소스들을 캐시에 저장하여 오프라인에서도 앱을 사용할 수 있게 합니다.
3. Network First 전략
개요
네트워크 요청을 먼저 시도하고 실패 시 캐시를 사용하는 전략으로 항상 최신 데이터를 우선합니다.
코드 예제
self.addEventListener('fetch', event => {
event.respondWith(
fetch(event.request).catch(() =>
caches.match(event.request)
)
);
});
설명
fetch 이벤트를 가로채서 네트워크 요청을 먼저 시도하고, 실패하면 캐시된 응답을 반환합니다.
4. Push Notification 구독
개요
사용자에게 푸시 알림을 보내기 위해 Push API를 사용하여 구독을 생성합니다.
코드 예제
navigator.serviceWorker.ready.then(registration => {
registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(publicKey)
}).then(sub => console.log('Subscribed:', sub));
});
설명
Service Worker가 준비되면 pushManager를 통해 구독을 생성하고, 서버와 통신할 수 있는 구독 정보를 받습니다.
5. Push 알림 수신
개요
서버에서 전송한 푸시 메시지를 수신하고 사용자에게 알림을 표시합니다.
코드 예제
self.addEventListener('push', event => {
const data = event.data.json();
event.waitUntil(
self.registration.showNotification(data.title, {
body: data.body, icon: '/icon.png'
})
);
});
설명
push 이벤트를 수신하면 showNotification API를 사용하여 사용자에게 시각적 알림을 표시합니다.
6. App 설치 프롬프트
개요
beforeinstallprompt 이벤트를 캡처하여 사용자가 원하는 시점에 PWA 설치를 유도합니다.
코드 예제
let deferredPrompt;
window.addEventListener('beforeinstallprompt', e => {
e.preventDefault();
deferredPrompt = e;
btnInstall.style.display = 'block';
});
설명
브라우저의 자동 설치 프롬프트를 막고, 나중에 사용자가 버튼을 클릭할 때 설치 프롬프트를 표시할 수 있습니다.
7. Web Manifest 설정
개요
manifest.json 파일을 통해 PWA의 이름, 아이콘, 테마 색상 등 앱의 메타데이터를 정의합니다.
코드 예제
{
"name": "My PWA App",
"short_name": "PWA",
"start_url": "/",
"display": "standalone",
"theme_color": "#4285f4",
"icons": [{"src": "/icon-192.png", "sizes": "192x192"}]
}
설명
Web App Manifest를 통해 홈 화면에 추가될 때의 아이콘, 이름, 표시 모드 등을 설정합니다.
8. Background Sync
개요
네트워크 연결이 불안정할 때 백그라운드에서 데이터 동기화를 수행합니다.
코드 예제
navigator.serviceWorker.ready.then(registration => {
return registration.sync.register('sync-posts');
});
self.addEventListener('sync', event => {
if (event.tag === 'sync-posts') {
event.waitUntil(syncPosts());
}
});
설명
Background Sync API를 사용하여 오프라인 상태에서 생성된 데이터를 네트워크 복구 시 자동으로 서버와 동기화합니다.
9. Share API 통합
개요
Web Share API를 사용하여 네이티브 앱처럼 콘텐츠를 공유할 수 있습니다.
코드 예제
async function shareContent() {
if (navigator.share) {
await navigator.share({
title: 'PWA Guide',
text: 'Check out this PWA!',
url: window.location.href
});
}
}
설명
navigator.share를 사용하면 운영체제의 기본 공유 기능을 활용하여 URL, 텍스트, 파일을 공유할 수 있습니다.
10. Badging API
개요
앱 아이콘에 배지를 표시하여 읽지 않은 알림 개수 등을 시각적으로 표현합니다.
코드 예제
if ('setAppBadge' in navigator) {
navigator.setAppBadge(5);
}
// 배지 제거
navigator.clearAppBadge();
설명
Badging API를 사용하여 홈 화면의 앱 아이콘에 숫자 배지를 표시하거나 제거할 수 있습니다.
11. Periodic Background Sync
개요
주기적으로 백그라운드에서 콘텐츠를 업데이트하여 앱을 열 때 최신 데이터를 표시합니다.
코드 예제
const registration = await navigator.serviceWorker.ready;
await registration.periodicSync.register('content-sync', {
minInterval: 24 * 60 * 60 * 1000 // 24시간
});
self.addEventListener('periodicsync', event => {
if (event.tag === 'content-sync') {
event.waitUntil(updateContent());
}
});
설명
Periodic Background Sync를 사용하면 정해진 간격으로 백그라운드에서 자동으로 콘텐츠를 동기화할 수 있습니다.
12. Cache Storage 관리
개요
오래된 캐시를 삭제하여 저장 공간을 효율적으로 관리하고 최신 버전을 유지합니다.
코드 예제
self.addEventListener('activate', event => {
const cacheWhitelist = ['v2'];
event.waitUntil(
caches.keys().then(names =>
Promise.all(names.map(name =>
!cacheWhitelist.includes(name) ? caches.delete(name) : null
))
)
);
});
설명
Service Worker 활성화 시 화이트리스트에 없는 오래된 캐시를 삭제하여 새 버전으로 업데이트합니다.
마치며
이번 글에서는 PWA Progressive Web App 최신기능에 대해 알아보았습니다. 총 12가지 개념을 다루었으며, 각각의 사용법과 예제를 살펴보았습니다.
관련 태그
#PWA #ServiceWorker #WebManifest #PushNotification #OfflineFirst