填寫這份《一分鐘調查》,幫我們(開發組)做得更好!去填寫Home

Service Worker 快速上手

Getting started with service workers

本文件解釋瞭如何在 Angular CLI 專案中啟用對 Angular Service Worker 的支援。稍後它會用一個簡單的範例來向你展示 Service Worker 實踐,包括載入和基礎的快取功能。

This document explains how to enable Angular service worker support in projects that you created with the Angular CLI. It then uses a simple example to show you a service worker in action, demonstrating loading and basic caching.

前提條件

Prerequisites

Angular Service Worker 簡介中的資訊有了基本的瞭解。

A basic understanding of the information in Introduction to Angular service workers.

為你的專案新增 Service Worker

Adding a service worker to your project

要讓你的專案支援 Angular Service Worker,可以使用 CLI 命令 ng add @angular/pwa。它會新增 service-worker 套件,並建立必要的支援檔案,小心翼翼地配置你的應用,以便使用 Service Worker。

To set up the Angular service worker in your project, use the CLI command ng add @angular/pwa. It takes care of configuring your app to use service workers by adding the service-worker package along with setting up the necessary support files.

ng add @angular/pwa --project *project-name*
      
      ng add @angular/pwa --project *project-name*
    

上述命令完成了如下步驟:

The above command completes the following actions:

  1. 把 @angular/service-worker 新增到你的專案中。

    Adds the @angular/service-worker package to your project.

  2. 在 CLI 中啟用 Service Worker 的建構支援。

    Enables service worker build support in the CLI.

  3. 在應用模組中匯入並註冊 Service Worker。

    Imports and registers the service worker in the app module.

  4. 修改 index.html 檔案:

    Updates the index.html file:

    • 包含要新增到 manifest.webmanifest 檔案中的連結。

      Includes a link to add the manifest.webmanifest file.

    • theme-color 新增 meta 標籤。

      Adds meta tags for theme-color.

  5. 建立圖示檔案,以支援安裝漸進式應用(PWA)。

    Installs icon files to support the installed Progressive Web App (PWA).

  6. 建立一個名叫 ngsw-config.json的 Service Worker 配置檔案,它會用來指定快取的行為以及其它設定。

    Creates the service worker configuration file called ngsw-config.json, which specifies the caching behaviors and other settings.

現在,建構本專案:

Now, build the project:

ng build --prod
      
      ng build --prod
    

現在,這個 CLI 專案就可以使用 Angular Service Worker 了。

The CLI project is now set up to use the Angular service worker.

Service Worker 實戰:嚮導

Service worker in action: a tour

本節用一個範例應用來示範一下 Service Worker 實戰。

This section demonstrates a service worker in action, using an example application.

http-server 啟動開發伺服器

Serving with http-server

由於 ng serve 對 Service Worker 無效,所以必須用一個獨立的 HTTP 伺服器在本地測試你的專案。 你可以使用任何 HTTP 伺服器。下面這個例子使用來自 npm 中的 http-server 套件。 為了減小埠衝突的可能性,我們在一個專用埠上進行測試。

Because ng serve does not work with service workers, you must use a separate HTTP server to test your project locally. You can use any HTTP server. The example below uses the http-server package from npm. To reduce the possibility of conflicts and avoid serving stale content, test on a dedicated port and disable caching.

要想使用 http-server 在包含這些 web 檔案的目錄上啟動服務,執行下列命令:

To serve the directory containing your web files with http-server, run the following command:

http-server -p 8080 -c-1 dist/<project-name>
      
      http-server -p 8080 -c-1 dist/<project-name>
    

最初的載入

Initial load

在伺服器執行起來之後,你可以在瀏覽器中訪問 http://localhost:8080/。你的應用像通常一樣載入。

With the server running, you can point your browser at http://localhost:8080/. Your application should load normally.

提示: 當測試 Angular Service Worker 時,最好使用瀏覽器中的隱身或隱私視窗,以確保 Service Worker 不會從以前的殘留狀態中讀取資料,否則可能導致意外的行為。

Tip: When testing Angular service workers, it's a good idea to use an incognito or private window in your browser to ensure the service worker doesn't end up reading from a previous leftover state, which can cause unexpected behavior.

注意: 如果沒有使用 HTTPS,那麼 Service Worker 只會在 localhost 上的應用中進行註冊。

Note: If you are not using HTTPS, the service worker will only be registered when accessing the app on localhost.

模擬網路出問題

Simulating a network issue

要想模擬網路出問題的情況,可以為你的應用禁用網路互動。在 Chrome 中:

To simulate a network issue, disable network interaction for your application. In Chrome:

  1. 選擇 Tools > Developer Tools (從右上角的 Chrome 選單)。

    Select Tools > Developer Tools (from the Chrome menu located at the top right corner).

  2. 進入 Network 頁

    Go to the Network tab.

  3. 勾選 Offline 複選框。

    Check the Offline box.

現在,本應用不能再和網路進行互動了。

Now the app has no access to network interaction.

對於那些不使用 Angular Service Worker 的應用,現在重新整理將會顯示 Chrome 的“網路中斷”頁,提示“沒有可用的網路連線”。

For applications that do not use the Angular service worker, refreshing now would display Chrome's Internet disconnected page that says "There is no Internet connection".

有了 Angular Service Worker,本應用的行為就不一樣了。重新整理時,頁面會正常載入。

With the addition of an Angular service worker, the application behavior changes. On a refresh, the page loads normally.

如果你看看 Network 頁,就會發現 Service Worker 是啟用的。

If you look at the Network tab, you can verify that the service worker is active.

注意,在 “Size” 列中,請求的狀態是 (from ServiceWorker)。 這表示該資源不是從網路上載入的,而是從 Service Worker 的快取中。

Notice that under the "Size" column, the requests state is (from ServiceWorker). This means that the resources are not being loaded from the network. Instead, they are being loaded from the service worker's cache.

什麼被快取了?

What's being cached?

注意,瀏覽器要渲染的所有這些檔案都被快取了。 ngsw-config.json 樣板檔案被配置成了要快取 CLI 用到的那些檔案:

Notice that all of the files the browser needs to render this application are cached. The ngsw-config.json boilerplate configuration is set up to cache the specific resources used by the CLI:

  • index.html.

  • favicon.ico.

  • 建構結果(JS 和 CSS 包)。

    Build artifacts (JS and CSS bundles).

  • assets 下的一切。

    Anything under assets.

  • 圖片和字型直接位於所配置的 outputPath (預設為 ./dist/<project-name>/) 或 resourcesOutputPath 下。 關於這些配置的更多資訊,請參閱 ng build

    Images and fonts directly under the configured outputPath (by default ./dist/<project-name>/) or resourcesOutputPath. See ng buildfor more information about these options.

注意如下兩個關鍵點:

Pay attention to two key points:

  1. 所產生的 ngsw-config.json 包括一個可快取字型和影象的有限列表。在某些情況下,你可能要按需修改這些 glob 模式。

    The generated ngsw-config.json includes a limited list of cacheable fonts and images extensions. In some cases, you might want to modify the glob pattern to suit your needs.

  2. 如果在生成了配置檔案之後修改了 resourcesOutputPathassets 的路徑,那麼就要在 ngsw-config.json 中手動修改這些路徑。

    If resourcesOutputPath or assets paths are modified after the generation of configuration file, you need to change the paths manually in ngsw-config.json.

修改你的應用

Making changes to your application

現在,你已經看到了 Service Worker 如何快取你的應用,接下來的步驟講它如何進行更新。

Now that you've seen how service workers cache your application, the next step is understanding how updates work.

  1. 如果你正在隱身視窗中測試,請開啟第二個空白頁。這會讓該隱身視窗和快取的狀態在測試期間持續活著。

    If you're testing in an incognito window, open a second blank tab. This will keep the incognito and the cache state alive during your test.

  2. 關閉該應用的頁面,而不是整個視窗。這也會同時關閉開發者工具。

    Close the application tab, but not the window. This should also close the Developer Tools.

  3. 關閉 http-server

    Shut down http-server.

  4. 接下來,對應用進行一些修改,並且觀察 Service Worker 安裝這些更新。

    Next, make a change to the application, and watch the service worker install the update.

  5. 開啟 src/app/app.component.html 供編輯。

    Open src/app/app.component.html for editing.

  6. 把文字 Welcome to {{title}}! 改為 Bienvenue à {{title}}!

    Change the text Welcome to {{title}}! to Bienvenue à {{title}}!.

  7. 再次建構並執行此伺服器:

    Build and run the server again:

ng build --prod http-server -p 8080 -c-1 dist/<project-name>
      
      ng build --prod
http-server -p 8080 -c-1 dist/<project-name>
    

在瀏覽器中更新你的應用

Updating your application in the browser

現在,看看瀏覽器和 Service Worker 如何處理這個更新後的應用。

Now look at how the browser and service worker handle the updated application.

  1. 再次在同一個視窗中開啟 http://localhost:8080,發生了什麼?

    Open http://localhost:8080 again in the same window. What happens?

錯在哪裡?哪裡也沒錯,真的。Angular Service Worker 正在做自己的工作,並且用它已經安裝過的版本提供服務,雖然,已經有新版本可用了。由於更關注速度,所以 Service Worker 並不會在啟動它已經快取過的版本之前先等待檢查更新。

What went wrong? Nothing, actually. The Angular service worker is doing its job and serving the version of the application that it has installed, even though there is an update available. In the interest of speed, the service worker doesn't wait to check for updates before it serves the application that it has cached.

如果你看看 http-server 的 log,就會發現 Service Worker 請求了 /ngsw.json 檔案,這是 Service Worker 正在檢查更新。

If you look at the http-server logs, you can see the service worker requesting /ngsw.json. This is how the service worker checks for updates.

  1. 重新整理頁面。

    Refresh the page.

Service Worker 在後臺安裝好了這個更新後的版本,下次載入或重新整理頁面時,Service Worker 就切換到最新的版本了。

The service worker installed the updated version of your app in the background, and the next time the page is loaded or reloaded, the service worker switches to the latest version.


關於 Angular Service Worker 的更多資訊

More on Angular service workers

你可能還對下列內容感興趣:

You may also be interested in the following: