“This is the fifth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

I wanted to continue updating Notification, but I felt that Service workers should be understood before Notification, so TODAY I will talk about Service workers first

Service Workers also enables you to handle push messages. Today, Service workers are a type of network worker that runs in a thread outside the main thread of the browser.

Because Service Workers operate independently of the application to which they are associated, Service Workers can receive messages even when the application is in the background or not open, or when the browser is closed.

The primary purpose of service workers is to act as a caching proxy, processing network requests and storing content for offline use, followed by handling push messages, which today’s example is push messages.

The service worker becomes idle when it is not in use and restarts the next time it is needed.

Now, if you have information that you need to persist and reuse across restarts, the Service Worker can work with the IndexedDB database.

limitations

This cache is persistent and independent of browser cache or network state. Now, due to the power of Service Workers and to prevent manin-the-middle attacks, service Workers can only be used for secure resources provided over TLS, requiring the HTTPS protocol, in order to avoid leaking the content of communication between users and servers. We will use localhost to test Service Works.

The life cycle

  • register
  • install
  • activate

There are also functional events such as

  • push
  • fetch
  • sync

Next, we implement offline application, that is, use Service workers to cache some files, so that the website can still be accessed offline, so as to enhance user experience.

By implementing offline applications, we will learn more about using service Workers and related apis and how to use them. Caching resources for your application will allow content to load quickly under all network conditions.

There are two specific appropriate caching behaviors that can be implemented through service workers. The first type of cache is to pre-cache resources at installation time. Examples include HTML, CCS, Javascript, images, etc. These resources are shared in your application and can be cached by Service Workers when the Web application is first opened.

Check whether the browser supports Service Workers

if('serviceWorker' in navigator){
    console.log('Service Worker Supported');
}
Copy the code

Registration Service Workers

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
Service Worker Supported
about.html:42 Live reload enabled.
main.js:6 Service Worker Registered
Copy the code

You can view registering service Workers on the Application page.

Then check Update on Reload to reload service Workers on refresh.

self.addEventListener('install'.() = >{
    console.log(`service worker: installed `)}); self.addEventListener('activate'.() = >{
    console.log(`service worker: activate `)});Copy the code

You can check Offline to simulate being Offline.

const cacheName = 'v1';

const cacheAssets = [
    'index.html'.'about.html'.'/css/style.css'.'/js/main.js'
]
Copy the code

Here we give the cache file

self.addEventListener('install'.(e) = >{
    console.log(`service worker: installed `);
    e.waitUntil(
        caches.
            open(cacheName)
            .then(cache= >{
                console.log(`service worker:caching files`)}})))Copy the code

Cache.addall () : cache.addall () : cache.addall () : cache.addall () : cache.addall () : cache.addall

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

These cached pages are still not accessible offline.

So let’s start by deleting other cached versions,

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