First you need to install callback as per you version name(ex: v22). So, we need to take the following steps:
1)Open a cache.
2)Cache our files.
3)Confirm whether all the required assets are cached or not.
For more clarity you can reach the below urls.
https://developers.google.com/web/fundamentals/primers/service-workers
Like below code.
var CACHE_NAME = 'my-site-cache-v1';
var urlsToCache = [
'/',
'/styles/main.css',
'/script/main.js'
];
self.addEventListener('install', function(event) {
// Perform install steps
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});
Then for access you need to use fetch
event of service worker.
Like below code.
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
return fetch(event.request);
}
)
);
});
For update and delete you can use activate
event of service worker. Please read the cacheWhitelist
properly. But,If you want to update you must be need to change the chachname/version
name of service worker. For delete you can direct delete using map()
.
Like below code.
self.addEventListener('activate', function(event) {
var cacheWhitelist = [cacheName];
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(cacheName) {
if (cacheWhitelist.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
}
})
);
})
);
});
I hope it's help you..!!