service worker


Posted by TempuraEngineer on 2022-02-27

service worker是甚麼

service worker是proxy servers(可視作連接web application、瀏覽器、網路的橋樑)。


Image credit: https://developers.google.com/web/tools/workbox/modules/workbox-strategies

如果網路暢通(且它只活在HTTPS環境)它會監聽request然後採取合適的動作,並更新存在其server的資產(各種web application)。當網路不順或斷掉的時候他會從快取挖出資產,藉此提升使用體驗。

service worker也可用於notification和背景執行的同步API。

Service workers essentially act as proxy servers that sit between web applications, the browser, and the network** (when available). They are intended, among other things, to enable the creation of effective offline experiences, intercept network requests and take appropriate action based on whether the network is available, and update assets residing on the server. They will also allow access to push notifications and background sync APIs.

The service worker is a web API that helps you cache your assets and other files so that when the user is offline or on slow network, he/she can still see results on the screen, as such, it helps you build a better user experience

註冊

navigator.serviceWorker.register(serviceWorker script路徑, options);

The register() method of the ServiceWorkerContainer interface creates or updates a ServiceWorkerRegistration for the given scriptURL. If successful, a service worker registration ties the provided script URL to a scope, which is subsequently used for navigation matching

navigator.serviceWorker.register('firebase-messaging-sw.js', {
    scope: 'firebase-cloud-messaging-push-scope'
});
  1. options
    • scope: 相對路徑,service worker控制的範圍,一般情況不可以比default還廣。default為script所在位置
    • type:service worker的類型。預設為classic。module的話因為script是ES module,可用import statement

2.script(上面的firebase-messaging-sw.js)

    importScripts('https://www.gstatic.com/firebasejs/8.2.5/firebase-app.js');
    importScripts('https://www.gstatic.com/firebasejs/8.2.5/firebase-messaging.js');
    try{
        firebase.initializeApp({
            messagingSenderId: '輸入key',
        });
        const messaging = firebase.messaging();
    }catch(err){
        console.log(err);
    }

script詳細看這

如果註冊成功會回傳ServiceWorkerRegistration,接下來會走「download、install、activate」的生命週期

方法

  • navigator.serviceWorker.register(script, options);

  • navigator.serviceWorker.getRegistration(scope url);
    回傳一個promise。如果輸入的路徑在註冊範圍內result為ServiceWorkerRegistration,反之為undefined

    navigator.serviceWorker.getRegistration('http://localhost:8080/firebase-cloud-messaging-push-scope');
    
  • navigator.serviceWorker.startMessages()

registerServiceWorker.js

如果在開專案時有開啟PWA設定,那在main.js裡會自動幫你引入registerServiceWorker.js

使用預設的PWA有以下功效

  1. precache所有你的網站的build files(就是vue-cli-service build會build出來的檔案)
  2. 如果快取裡面已經有的話,直接去挖你的網站快取
  3. 可以直接用common events
// 預設的registerServiceWorker.js長這樣,已經把common events都寫好了
// 更詳細可以去node_modules看register-service-worker的index.js

import { register } from 'register-service-worker'

if (process.env.NODE_ENV === 'production') {
  register(`${process.env.BASE_URL}service-worker.js`, {
    ready () {
      console.log(
        'App is being served from cache by a service worker.\n' +
        'For more details, visit https://goo.gl/AFskqB'
      )
    },
    registered () {
      console.log('Service worker has been registered.')
    },
    cached () {
      console.log('Content has been cached for offline use.')
    },
    updatefound () {
      console.log('New content is downloading.')
    },
    updated () {
      console.log('New content is available; please refresh.')
    },
    offline () {
      console.log('No internet connection found. App is running in offline mode.')
    },
    error (error) {
      console.error('Error during service worker registration:', error)
    }
  })
}

當然如果不想要用預設的也可以全部自己做,也可以用預設的去修改


📖

Service_Worker_API
What does registerServiceWorker do in React JS?
How to Enable Offline Mode for Your Gatsby Site
Vue PWA caching routes in advance


#service worker







Related Posts

 使用vue-google-maps套件實作地圖(二)

使用vue-google-maps套件實作地圖(二)

Day 93

Day 93

C# DataGirdView相關應用

C# DataGirdView相關應用


Comments