What is a Service Worker

A Service worker is an event-driven worker registered with a specified source and path. It uses JavaScript to control associated pages or websites, intercepts and modifies access and resource requests, and cache resources in a fine-grained manner. Service workers enable your application to first access local cached resources, including static resources such as JS, CSS, PNG, JSON, etc.

Characteristics of Service workers

  1. Independent of the main JavaScript thread (which means that running it doesn’t affect the load performance of our main process at all)
  2. Design for full asynchrony, with heavy use of promises (since Service workers typically wait for responses to continue, promises are perfect)
  3. Can’t access DOM, can’t use XHR and localStorage
  4. Service workers can only be hosted by HTTPS (for security reasons)

The life cycle of the Service Worker

The Service Worker usage

registered

Using ServiceWorkerContainer. The register () method is a registered service worker.

// sw.js
if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/loading-page-sw.js', {scope: '/'}).then(function(reg) {
	// Reg can view the state and scope of the current sw
    }).catch(function(error) {
        // registration failed
        console.log('Registration failed with ' + error);
    });
}

Copy the code

Cache handling

  • Caches. Open (SW_VERSION) : opens the cache. SW_VERSION: opens the version
  • Cache. addAll(CACHE_FILE_LIST) : adds a cache. CACHE_FILE_LIST: lists the file paths
  • Caches. Keys () : Gets a locally stored version collection
  • Caches. Delete (key): deletes the cache information of a certain version
  • Cache. put(event.request, responseClone) : Manually add cache. The parameters are request and response

The complete code is attached below

// loading-page-sw.js
const SW_VERSION = 'V1';
const CACHE_FILE_TYPE = [ 'js'.'css'.'html'.'jpg'.'json'.'png''mp3'.'wav'.'mp4'.'ttf'];
// Confirm the cached file
const CACHE_FILE_LIST = [];
// List of files to fool
const IGNORE_FILE_LIST = [
  '/test/index.js',];/** * Specifies the file type *@param {*} url 
 */
function isAcceptFile(url) {
  var r = new RegExp("\ \. (" + CACHE_FILE_TYPE.join('|') + "$");
  return r.test(url);
}
/** * Check the file name */
function checkIgnoreFileName(url) {
  var r = new RegExp("(" + IGNORE_FILE_LIST.join('|') + "$");
  return r.test(url);
}
self.addEventListener('install'.function(event) {
    event.waitUntil(
      caches.open(SW_VERSION).then(function(cache) {
        returncache.addAll(CACHE_FILE_LIST); })); }); self.addEventListener('activate'.function(event) {
    var cacheWhitelist = [SW_VERSION];
    event.waitUntil(
      caches.keys().then(function(keyList) {
        return Promise.all(keyList.map(function(key) {
          if (cacheWhitelist.indexOf(key) === -1) {
            returncaches.delete(key); }})); })); }); self.addEventListener('fetch'.function(event) {
    const {method, url} = event.request;
    event.respondWith(
      caches.match(event.request).then(function(response) {
          if(response ! = =undefined) {
              return response;
          } else {
              return fetch(event.request).then(function (response) {
                  let responseClone = response.clone();
                  if (method === 'POST') {
                    return response
                  }
                  if(! isAcceptFile(url)) {return response
                  }
                  if (checkIgnoreFileName(url)) {
                    return response
                  }
                  caches.open(SW_VERSION).then(function (cache) {
                    cache.put(event.request, responseClone);
                  });
                  return response;
              }).catch(function (error) {
                 return Promise.reject(error); }); }})); });Copy the code

Service worker debugging check

Check the service worker process status

  • The service worker actually provides a local caching service, so it is similar to checking localStorage. Open Google Browser debug Center, and under the Application bar, you can see service Woerkers, as shown in the picture:

  • You can Unregister the service worker process on the right.

View local storage information

  • The service worker will store the file of the corresponding version locally according to our version, as shown in the figure below:

  • V1: is our customized version number
  • The cached files are listed as a list, with information such as name, return type, context length, cache time, and so on.

HTTP cache

When a page makes a resource request, the browser responds as quickly as possible through caching and other means to avoid unnecessary HTTP consumption. This is why we often see: Memory Cache, Disk Cache, Push Cache, and now ServiceWorker. Here’s a simple comparison:

ServiceWorker

When we enable ServiceWorker, the browser shows that our resources are from ServiceWorker. The caching of Service workers is different from other caching mechanisms. We have free control over caching, file matching, read caching, and it is persistent. The ServiceWorker rerequests data if it misses a hit.

Memory Cache

A Memory Cache is a Cache in Memory, which is very fast to read resources in Memory. While a Memory Cache is fast and efficient, it is short-lived and is freed when the browser or TAB page is closed. And too much memory can cause the browser to take up too much memory on the computer, you know, a computer’s memory is limited.

Disk Cache

Disk Cache stores resources on hard disks. The read speed is lower than that of Memory Cache, but it can be stored for a long time and has a large coverage. The Disk Cache performs caching based on the Cache policies enabled by the HTTP header, namely strong caching and negotiated caching.

Push Cache

Push Cache is used when all three caches fail. It exists only for sessions, is released once the Session ends, and has a short cache time.

  • We can view the caching method of resources most intuitively through network. As shown in the figure:

Service Worker logout and deletion

We have explained the usage of the Service Worker and compared it with other caches. Finally, let’s talk about how to unregister Service workers and remove local caches.

The cancellation

Unregister is done by calling the unregister() function as follows:

if ('serviceWorker' in navigator) {
    navigator.serviceWorker.getRegistrations()
    .then(function(registrations){
        registrations.forEach(function(registration) { registration.unregister(); })})}Copy the code

delete

Remove the pair by calling caches.delete() with the following code:

if (window.caches && caches.keys) {
    caches.keys().then(function(keys) {
        keys.forEach(function(key) {
            caches.delete(key)
        })
    })
}
Copy the code

Write in the last

As the Service Worker is a separate operating environment, independent of the main JavaScript process, the navigator. UserAgent obtained by the front-end is different from the userAgent obtained by the background. If Service worker needs to be used in the project, it is necessary to observe whether its own services are affected, and conduct more tests and observations.