javascript
Add service worker to your website
//CREATE SERVICE WORKER FILE ON ROOT NAMED AS service-worker.js(Name does not matter)
var cacheName = 'my-web-cache';
var filestoCache = [
'/css/style.css',
'/css/main.css',
'/js/main.js',
'/images/logo.png'
];
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(cacheName)
.then(function(cache) {
console.log('Opened cache');
return cache.addAll(filestoCache);
})
);
});
//CALL SERVICE WORKER FILE AND INSTALL IT(GENERALLY FORM inde.html or other pages)
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/service-worker.js').then(function(registration) {
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}, function(err) {
console.log('ServiceWorker registration failed: ', err);
});
});
}
If you want to add cache management on your website that can even work offline, you can use service workers for that. It helps you to cache files like images, stylesheets, scripts and even it can cache your whole webpage. The integration is really easy that you just need to create a service worker file in js format and register the service worker by calling 'navigator.serviceWorker.register' method.
Was this helpful?
Similar Posts
- Remove all cookies from the current website using Javascript
- Install redux form in your app
- Write a function to check if milk exists in your array
- Add class to an element in javascript
- Add new item at first position of array using unshift() method Javascript
- Add redux form reducer to store
- Add Input fields in Redux Form