Read Time:1 Minute, 14 Second
Service Worker:
웹페이지와 별개로 브라우저가 백그라운드에서 실행시키는 자바스크립트 코드. 푸쉬, 동기화, 오프라인 모드 지원
https://developers.google.com/web/fundamentals/primers/service-workers/
Workerbox:
구글에서 제공하는 자바스크립트 라이브러리로써 웹앱의 오프라인 지원을 쉽게 할 수 있도록 해줌.
https://developers.google.com/web/tools/workbox/
Workerbox 설치 법:
Step 1/2: In the bottom of your website, add following Javascript code snippet:
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/service-worker.js')
.then(function (registration) {
console.log(
'Service Worker registration successful with scope: ',
registration.scope
);
})
.catch(function (err) {
console.log('Service Worker registration failed: ', err);
});
}
Step 2/2: Create service-workers.js
and add following snippet:
importScripts(
"https://storage.googleapis.com/workbox-cdn/releases/3.6.1/workbox-sw.js"
);
if (workbox) {
const version = "v1";
workbox.core.setCacheNameDetails({
prefix: "sample-project",
suffix: version,
precache: "precache-name",
runtime: "runtime-name"
});
const cssCacheName = "css-cache-" + version;
const imageCacheName = "image-cache-" + version;
console.log(`Yay! Workbox is loaded 🎉`);
workbox.routing.registerRoute(
new RegExp(".*.js"),
workbox.strategies.networkFirst()
);
workbox.routing.registerRoute(
// Cache CSS files
/.*\.css/,
// Use cache but update in the background ASAP
workbox.strategies.staleWhileRevalidate({
// Use a custom cache name
cacheName: cssCacheName
})
);
workbox.routing.registerRoute(
// Cache image files
/.*\.(?:png|jpg|jpeg|svg|gif)/,
// Use the cache if it's available
workbox.strategies.cacheFirst({
// Use a custom cache name
cacheName: imageCacheName,
plugins: [
new workbox.expiration.Plugin({
// Cache only 20 images
maxEntries: 20,
// Cache for a maximum of a week
maxAgeSeconds: 7 * 24 * 60 * 60
})
]
})
);
} else {
console.log(`Boo! Workbox didn't load 😬`);
}