“This is the sixth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
Registration service workers
To install a Service worker, you need to register it. The purpose of the registration is to tell the browser where the service Workers file is, and then the browser starts installing Service Workers in the background.
Here you can introduce the sw_cache_page.js file in the main.js file referenced in the index.html file under the project
if('serviceWorker' in navigator){
console.log('Service Worker Supported');
window.addEventListener('load'.function(){
navigator.serviceWorker
.register('.. /sw_cache_page.js')
.then(reg= > console.log(`Service Worker Registered`))
.catch(err= > console.error(err))
})
}
Copy the code
In the code, we first check if there is a serviceWorker object in the Navigator object, and then call the navigator. ServiceWorker object register method to register the Service Workers. This method returns a Promise that can be processed after a successful installation of the Service worker.
Then specify the scope of service workers with registration.scope. You can try to register a Service worker each time the page loads.
The browser will only register service Workers when the service Workers is first loaded or updated. The scope of service Workers is used to specify the path from which service Workers will intercept requests. The default scope is the path to the Service Workers file and extends to all directories below it. If the Service Workers script, for example, serviceworker.js, is located in the root directory, the service worker will control requests for all files from that domain.
If /app/ is set at the time of registration, service workers will control the request of /app, /app/lower and /app/lower/lower pages. But it does not include requests for the app directory and pages in its upper directory.
.register('.. /sw_cache_page.js', {scope:'/app/'
})
Copy the code
Install event
Once the browser successfully registers a service worker, the Install event is triggered. The Install event is triggered when the service worker is installed for the first time, or when the page detects a change in the service worker code. You can perform operations in the Install event callback. Caching requests and resources can be handled in install events.
self.addEventListener('install'.(e) = >{
console.log(`service worker: installed `);
e.waitUntil(
caches.
open(cacheName)
.then(cache= >{
console.log(`service worker:caching files`)
cache.addAll(cacheAssets)
})
.then(() = >self.skipWaiting())
)
})
Copy the code
Activate the event
After a successful installation, it transitions to an activation event, and the service worker controls all pages loaded in its scope and intercepts network requests accordingly. The application cache can be cleared of versions during activation.
However, the page being opened in your application will not be in the scope of the service worker. Because when the page is opened, the service worker is not loaded.
To put the currently open page under the control of the service worker, you must reload the page or pages. Until then, requests from this page will bypass the service worker and operate as usual. The service worker keeps control as long as pages that depend on that particular version are opened. This ensures that only one version of the service worker is running at any one time.
If a new service worker is installed on a page with an existing service worker, the new Srvice worker will not immediately take over the page from the original service worker. The page cannot be taken over until the original service worker is deleted.
self.addEventListener('activate'.e= >{
console.log(`service worker: activate `);
e.waitUntil(
catches.keys().then(cacheNames= > {
return Promise.all(
cacheNames.map(cache= >{
if(cache ! = cacheName){console.log('Service worker: clearing old cache');
return caches.delete(cache)
}
})
)
})
)
})
Copy the code
event-driven
Note that you can force a new service worker to be activated programmatically through self.skipwaiting ().
Service Workers are event-driven. Installl and Activate events raise events that the service worker can respond to. The install event is when you should prepare for using the service worker, for example by creating a cache and adding resources to it. The Activate event is a good time to clean up old caches and anything else related to previous versions of Service Workers. The ServiceWorker can receive messages from other scripts through message events.
For service workers it is event-driven, except for install described above
There are also functional events, such as FETCH, Push, and sync, to which service workers can respond. To view the Service Worers, navigate to the Service Worker in your browser’s development tools.
self.addEventListener('fetch'.e= > {
console.log('service Working:Fetching')
e.respondWith(
fetch(e.request).catch(() = >{ caches.match(e.request); }})))Copy the code