Thoughts on service workers

What?

How?

Quick learning

  • Add the following script to the HTML

    if (navigator.serviceWorker ! = null) {

    navigator.serviceWorker.register('/service-worker.js')

    .then(function(registration) {

    console.log('Registered events at scope: ', registration.scope);

    });

    } else {

    Console (' sw not supported ')

    }

    Copy the code
  • service-worker.js

    var cacheStorageKey = 'blog-pwa-2018060100'

    var cacheList = [

    '/',

    "/index.html",

    "/statics/css/swiper.css",

    "/statics/js/swiper.js",

    "/statics/images/1.jpeg",

    "/statics/images/6.jpeg",

    "/statics/images/7.jpeg"

    ]



    this.addEventListener('install', e => {

    e.waitUntil(

    caches.open(cacheStorageKey)

    .then(cache => cache.addAll(cacheList))

    .then(() => self.skipWaiting())

    )

    })



    this.addEventListener('fetch', function(e) {

    e.respondWith(

    caches.match(e.request).then(function(response) {

    if (response ! = null) {

    return response

    }

    return fetch(e.request.url)

    })

    )

    })

    Copy the code
  • After the above processing, the site can simply have offline ability.

Something to think about

  • How to update service-worker.js quickly and easily?
    • Since service-worker.js needs to be homologous with the site, the project separated at the front and back ends needs the back end to forward the request of service-worker.js to a resource controlled by the front end
    • If the site’s HTML is controlled by the front-end rather than the back-end template, the front-end needs to update the service-worker request when it goes live, with either a timestamp or an MD5 stamp to prevent it from being cached by HTTP
    • If your site’s HTML is not controlled by the front end, it is best to set it to no cache time, or a very short cache time, such as 5s, in order to keep service-worker.js up to date. Or the request URL is automatically stamped each time, which is essentially no cache time. Avoid the need to update backend templates every time you go online.
  • How do I update resources cached by serviceWorker?
    • Updating service-worker.js re-executes events such as Install Actived, in which old caches are removed and new caches are added
    • The fetch will be executed because the old activated service worker is still running. Cache. Match is used in fetch to determine whether the cache has been hit. Cache. match is a request match, so if the URL does not change, it will return true, so that response is directly fetched from the cache, causing the resource fetched from the previous version when the page is opened for the first time.
    • So to update on the front end, the URL must change to update correctly the first time it is opened
  • Automatic generation of service-worker.js?
    • Sw-precache and SW-Toolbox are early tools developed by Google; Sw-precache is a cache tool for the cache-first policy, which automatically generates sw.js based on the hash file. After the fetch hits the cache, it directly returns to the cache and then adds or deletes the cache based on the latest cache list. Sw-toolbox is used to cache some third-party resources and added the ability to customize caching strategies based on routes
    • Google will no longer maintain either tool, but the ultimate solution is WorkBox, which is more feature-rich and easier to use with plug-ins.
    • Workbox-webpack-plugin NPM package, CLI, Webpack workbox-webpack-plugin

How much benefit?

  • Need an offline experience?
    • Presentation is fine, but for projects that require online availability, it may not really be necessary.
    • The offline function can ensure the availability of low-speed network to a certain extent
  • What are the advantages of the SW cache over the normal HTTP cache?
    • More control, more granularity, caching time, updates are all done by the front-end code, rather than configuration on servers like Nginx.
    • There should be no difference in speed, it’s all cache, and it should all be stored on hard disk.
  • Push notification
    • Unavailable in China

What are the risks with this new technology

  • Does it increase the likelihood of a white screen?
    • Add sw, and the front end controls the return of the request. Request directly in sw for some logical judgment, and then either from the cache, or directly to the CDN to obtain, then the SW needs to consider all kinds of circumstances, do a good bottom, to avoid the problem of SW, resulting in the request error. Sw is best written with a script generated by SW-Precache or Workbox, or with reference to the script generated by it.
  • Browser compatibility
    • At present, BOTH IE and Safari have supported SW, but the apis and methods used in it, such as Cache and Fetch, are not well compatible, so we need to make a judgment

Refer to the article

Service worker DRAFT MDN Service worker API website Incremental Enhancement Experience (PWA) transformation: PWA practice with Service Worker and cacheStorage and offline development sw-precache sw-toolbox workbox