---
# System prepended metadata

title: '[5.Assets and data](https://web.dev/learn/pwa/assets-and-data/) 資產和數據'
tags: [PWA]

---

###### tags: `PWA` 

# [5.Assets and data](https://web.dev/learn/pwa/assets-and-data/) 資產和數據

A Progressive Web App is a website; all its assets are the same as on the web, but with new tools to make those assets load fast when online and available when offline.

Progressive Web App 是一個網站；它的所有資產都與網絡上的相同，但使用新工具可以使這些資產在在線時快速加載並在離線時可用。

## App components 應用元件

Developing an application typically involves several assets and resources, from the logic and code (compiled or not) to the user interface elements such as screen designs, images, logos, and fonts.

開發應用程序通常涉及多種資產和資源，從邏輯和代碼（編譯或未編譯）到用戶界面元素，如屏幕設計、圖像、徽標和字體。

A Progressive Web App is a website, so all its assets are the same as on the web:

Progressive Web App 是一個網站，因此它的所有資產都與網絡上的相同：

* HTML for content and initial page rendering.
* JavaScript for logic, including the ability to run WebAssembly modules (compiled code) and render 2D and 3D hardware-optimized graphics.
* CSS for layout, styling, and animations.
* Videos in web formats, such as MPEG-4 and WebM.
* Web fonts.
* Data in JSON or other formats.
* 用於內容和初始頁面呈現的 HTML。
* 用於邏輯的 JavaScript，包括運行 WebAssembly 模塊（編譯代碼）和渲染 2D 和 3D 硬件優化圖形的能力。
* 用於佈局、樣式和動畫的 CSS。
* Web 格式的影片，例如 MPEG-4 和 WebM
* 網頁字體
* JSON 或其他格式的數據。




By default, websites download assets over the network, [starting with HTML](https://web.dev/critical-rendering-path/) and continuing to the rest of the resources.

默認情況下，網站通過網絡下載資產，從 HTML 開始，然後繼續到其餘資源。

Managing those resources to load fast and be available offline has been a challenge for the web. Nowadays, PWAs use capabilities previously associated only with platform-specific apps.

管理這些資源以快速加載和離線使用一直是網絡面臨的挑戰。如今，PWA 使用以前僅與特定平台應用程序關聯的功能。






## Platform-specific apps vs. PWA 特定於平台的應用程序與 PWA

When you install a platform-specific app you are typically downloading a package that includes all the app's assets: code, images, fonts, videos, and so on. Therefore, all these resources are available, from your device storage, even when the app is offline.

當您安裝特定於平台的應用程序時，您通常會下載一個包，其中包含該應用程序的所有資產：代碼、圖像、字體、視頻等。因此，即使應用處於離線狀態，所有這些資源都可以從您的設備存儲中獲得。

On the other hand, a classic website needs a network connection to download the assets when required. If you are offline, you will see an error from the browser as there are no assets client-side.

另一方面，經典網站需要網絡連接才能在需要時下載資產。如果您處於離線狀態，您將在瀏覽器中看到錯誤消息，因為客戶端沒有資產。

The PWA approach enhances the traditional web experience by making some or all the assets available client-side as with platform-specific apps. Therefore, when you open a PWA, the initial rendering can be as instantaneous as a platform app because the assets are available without going to the network.

PWA 方法通過使部分或所有資產在客戶端可用，就像特定於平台的應用程序一樣，增強了傳統的 Web 體驗。因此，當您打開 PWA 時，初始渲染可以像平台應用程序一樣即時，因為資源無需聯網即可使用。

<div style="background-color:#deeafd;padding:1rem;line-height:1.9;margin-top:1rem;color:#174ea6">

An app that is available offline will always render a basic user interface instead of a technical error from the operating system or browser. Some apps still offer all their functionality, some a limited experience, and others a simple message with the app's branding. This applies to both platform-specific apps and PWAs.
    
</div>

<div style="background-color:#deeafd;padding:1rem;line-height:1.9;margin-top:1rem;color:#174ea6">

離線可用的應用程序將始終呈現基本用戶界面，而不是操作系統或瀏覽器的技術錯誤。一些應用程序仍然提供所有功能，一些提供有限的體驗，而另一些則提供帶有應用程序品牌的簡單消息。這適用於特定於平台的應用程序和 PWA。
    
</div>

## Caches and storage 緩存和存儲

Since the beginning of the web, developers have not had complete control of how a resource is cached. The browser is in charge of the HTTP cache and it may or may not cache and serve resources based on different policies. Other storage options like Web Storage and IndexedDB were meant to save simple data and objects.

自 Web 出現以來，開發人員一直無法完全控制資源的緩存方式。瀏覽器負責 HTTP 緩存，它可能會或可能不會根據不同的策略緩存和提供資源。 Web Storage 和 IndexedDB 等其他存儲選項旨在保存簡單的數據和對象。

PWAs don't need to rely on those policies alone for their content. Instead, we have solutions today to gain better control over when and how to cache resources and when and how to deliver them locally: the Cache Storage API. The web has a few of client-side storage solutions available:

PWA 的內容不需要單獨依賴這些策略。相反，我們今天有解決方案來更好地控制何時以及如何緩存資源以及何時以及如何在本地交付它們：Cache Storage API。 Web 有一些可用的客戶端存儲解決方案：

**Web storage**: Includes <kbd> localStorage </kbd>  and <kbd>sessionStorage </kbd> . These APIs store simple key/value string pairs. Web storage is limited, and has a synchronous API, so it should be avoided whenever possible.

**Web 存儲：** 包括 localStorage 和 sessionStorage 。這些 API 存儲簡單的鍵/值字符串對。 Web 存儲是有限的，並且具有同步 API，因此應盡可能避免。

**IndexedDB**: An object-based database (No-SQL) with an asynchronous API that is good for web performance. IndexedDB can store structured and binary data client-side. It is typically what you will use to store data, like what you'd get from or send as an API request. It's also useful to save data locally immediately and later on sync it to the server. The [IndexedDB](https://developer.mozilla.org/zh-CN/docs/Web/API/IndexedDB_API) API is used to interact with the database.


**IndexedDB：** 一種基於對象的數據庫（No-SQL），具有異步 API，有利於 Web 性能。 IndexedDB 可以在客戶端存儲結構化和二進制數據。它通常是您將用來存儲數據的內容，例如您從 API 請求中獲取或發送的內容。立即將數據保存在本地並稍後將其同步到服務器也很有用。 IndexedDB API 用於與數據庫交互。

**Cache storage**: A collection of HTTP request and response pairs you can use to store and retrieve resources — with their HTTP headers — exactly as they are delivered from the server. The [Cache Storage API](https://developer.mozilla.org/zh-CN/docs/Web/API/CacheStorage) allows you to store, retrieve, update and delete network requests, for example for your assets, even when offline.

**緩存存儲：** 一組 HTTP 請求和響應對，您可以使用它們來存儲和檢索資源（及其 HTTP 標頭），與從服務器交付的資源完全一樣。緩存存儲 API 允許您存儲、檢索、更新和刪除網絡請求，例如您的資產，即使在離線時也是如此。

<div style="padding:1rem;background-color:#fff5e3;margin-bottom:1em">
    

<div style="display:flex">
    
:warning:
       <p style="color:#c34900;margin-top:-1.5em">
       Caution
       </p> 
</div>
    

<p style="color:#c34900;">
You may have heard about WebSQL and ApplicationCache. These two solutions are deprecated, and you shouldn't use them in your PWA.
</p>

</div>



<div style="padding:1rem;background-color:#fff5e3;margin-bottom:1em">
    

<div style="display:flex">
    
:warning:
       <p style="color:#c34900;margin-top:-1.5em">
       Caution
       </p> 
</div>
    

<p style="color:#c34900;">
您可能聽說過 WebSQL 和 ApplicationCache。這兩個解決方案已棄用，您不應在 PWA 中使用它們。
</p>

</div>

## The need for service workers 對緩存的需求

A PWA can store its assets in Cache Storage and IndexedDB, but how can we use those assets to deliver a fast and offline experience to your users. The answer? Service workers.

PWA 可以將其資產存儲在緩存存儲和 IndexedDB 中，但我們如何使用這些資產為您的用戶提供快速的離線體驗。答案？服務人員。

With a service worker, you can serve assets without going to the network, send notifications to a user, add a badge to your PWA icon, update content in the background, and even make your whole PWA work offline. Learn more about service workers in the [next chapter](https://web.dev/learn/pwa/service-workers/).

使用 service worker，您可以在不進入網絡的情況下提供資產、向用戶發送通知、為您的 PWA 圖標添加徽章、在後台更新內容，甚至讓您的整個 PWA 離線工作。在下一章中了解更多關於服務工作者的信息。


## Offline-ready 離線準備

Users expect your application to offer a fast and always-ready experience. That means your app should work offline.

用戶希望您的應用程序能夠提供快速且隨時可用的體驗。這意味著您的應用程序應該可以離線工作。

Being offline-ready doesn't mean that all your content or services should be available without a network connection. Having at least a basic experience when the user is offline, like a page that asks you to connect to the Internet to continue, is one of the [requirements](https://web.dev/learn/pwa/getting-started/) of being a Progressive Web App. In some browsers this is a must-have feature to pass the PWA installation criteria. Displaying your PWA's user interface, along with cached content, is better. Letting users continue using your whole PWA and syncing server changes when they're back online is the gold standard for working offline.

離線就緒並不意味著您的所有內容或服務都可以在沒有網絡連接的情況下使用。當用戶離線時至少有基本的體驗，比如一個要求你連接到互聯網才能繼續的頁面，這是成為漸進式 Web 應用程序的要求之一。在某些瀏覽器中，這是通過 PWA 安裝標準的必備功能。顯示 PWA 的用戶界面以及緩存的內容會更好。讓用戶繼續使用您的整個 PWA 並在他們重新聯機時同步服務器更改是離線工作的黃金標準。

To make your app available offline, you will need to cache the assets necessary for your offline experience and make your service worker serve them later. Make sure to add the offline assets to your cache before you need them. This is a particular case where you cannot cache them when requested.

要使您的應用程序可離線使用，您需要緩存離線體驗所需的資產，並讓您的服務人員稍後為它們提供服務。確保在需要之前將離線資產添加到緩存中。這是一種特殊情況，您無法在請求時緩存它們。

<div style="background-color:#deeafd;padding:1rem;line-height:1.9;margin-top:1rem;color:#174ea6">

Asset caching happens independently from PWA installation, and will work even from a browser tab, allowing for faster asset delivery and an offline experience regardless of how a user chooses to use your PWA.
    
</div>

<div style="background-color:#deeafd;padding:1rem;line-height:1.9;margin-top:1rem;color:#174ea6">

資產緩存獨立於 PWA 安裝發生，甚至可以在瀏覽器選項卡中運行，無論用戶選擇如何使用您的 PWA，都可以實現更快的資產交付和離線體驗。
    
</div>

## Frequently used cache approaches   常用的緩存方法

In your PWA, you are in charge of all the decisions. You can choose the best approach to cache or install assets based on your needs. Some decisions to make are:

在你的 PWA 中，你負責所有的決定。您可以根據需要選擇緩存或安裝資產的最佳方法。需要做出的一些決定是：

* Precaching: pick the assets you'd like to install on the first load; those should include the HTML and the minimal assets to render the app. When using precache keep in mind you are using the device's space and network. Be conscious and responsible when downloading assets and caching them.
* Cache as needed: used to add assets to the cache when they are requested. Typically these are assets that can change independently of your app version, like images or content. See the [caching](https://web.dev/learn/pwa/caching/) section for different strategies on how to cache as needed.
* APIs and web services: API calls can be cached; or, instead of caching the API responses, you can store their data in IndexedDB.
* 預緩存：選擇你想在第一次加載時安裝的資產；這些應該包括 HTML 和呈現應用程序的最小資產。使用預緩存時請記住，您正在使用設備的空間和網絡。下載資產和緩存它們時要有意識和負責任。
* 根據需要緩存：用於在請求時將資產添加到緩存中。通常這些是可以獨立於您的應用程序版本而更改的資產，例如圖像或內容。有關如何根據需要進行緩存的不同策略，請參閱緩存部分。
* API 和 Web 服務：可以緩存 API 調用；或者，您可以將它們的數據存儲在 IndexedDB 中，而不是緩存 API 響應。


<div style="padding:1rem;background-color:#faf6fe;color:#6001ff;">
    
<span style="display:flex">
    
:bulb: 
       <p style="color:#6001ff;margin-top:-1.5em">
       Gotchas陷阱
       </p> 
</span>
    
<p style="color:#6001ff;">
    
With platform-specific apps, the most common pattern is to include all the app's assets in its package; that's why these apps are commonly larger than 500 MB. On the other hand, A PWA can initially install only the minimum set of resources to offer an offline and fast experience and download the rest later, with PWAs using considerably less storage on installation.
    
</p>

</div>

<div style="padding:1rem;background-color:#faf6fe;color:#6001ff;margin-top:1rem">
    
<span style="display:flex">
    
:bulb: 
       <p style="color:#6001ff;margin-top:-1.5em">
       Gotchas陷阱
       </p> 
</span>
    
<p style="color:#6001ff;">
    
對於特定於平台的應用程序，最常見的模式是將應用程序的所有資產包含在其包中；這就是為什麼這些應用程序通常大於 500 MB。另一方面，PWA 最初只能安裝最少的資源集以提供離線和快速體驗，然後再下載其餘資源，PWA 在安裝時使用的存儲空間要少得多。
    
</p>

</div>

## Updating assets 更新資產

In the standard app model for app catalog installed apps, when developers need to update their app, they publish a new package. Users need to download the whole package again, even if most of the assets haven't changed. With PWAs, using the approaches on the section above, you decide how and when to update assets. Here are different options for how to update assets:
在應用目錄安裝應用的標準應用模型中，當開發人員需要更新他們的應用時，他們會發布一個新包。用戶需要重新下載整個包，即使大部分資產沒有改變。使用 PWA，使用上一節中的方法，您可以決定如何以及何時更新資產。以下是有關如何更新資產的不同選項：

* Full Update: in this case, every time you make a change in the app, even a minor one, your code will download all the assets again in the cache.
* Partial Update: in this approach, you create a method to define which assets have been updated, and you update only those, with or without the user's intervention.
* Continuous Update: using this technique, your assets will be checked and updated automatically on every PWA usage individually
* 應用安裝模型模型中中，噹噹中需要的的應用應用時，他們時時時，他們他們時，他們他們他們他們他們發布一一個新新新包。。用戶用戶用戶需要需要重新個個個包包包包方法，您可以決定如何以及何時更新資產。以下是有關如何更新資產的不同選項：
* 部分更新：在這種方法中，您創建一個方法來定義哪些資產已被更新，並且您只更新那些，有或沒有用戶干預。
* 持續更新：使用這種技術，您的資產將在每次 PWA 使用時自動檢查和更新

<div style="background-color:#deeafd;padding:1rem;line-height:1.9;margin-top:1rem;color:#174ea6">

When caching assets, you need to decide on a cache swap or clean up policy that defines when the user will see an updated asset; taking into account storage usage and the balance between a fast experience and displaying a slightly stale asset.
    
</div>

<div style="background-color:#deeafd;padding:1rem;line-height:1.9;margin-top:1rem;color:#174ea6">

緩存資產時，您需要決定緩存交換或清理策略，以定義用戶何時會看到更新的資產；考慮到存儲使用情況以及快速體驗和顯示稍微陳舊的資產之間的平衡。
    
</div>

## Size and Lifespan 尺寸和壽命

Usually platform-specific apps don't deal with size limits; at installation, apps can be gigabytes or more in size. As long as the device has the capacity the installation will be allowed. Also, while the app is installed, it will use that total amount of storage no matter if you use the app or not. Storage is handled differently for PWAs. The browser will store your assets based on policies that you define in your PWA's logic.

通常特定於平台的應用程序不處理大小限制；安裝時，應用程序的大小可能為千兆字節或更多。只要設備具有容量，就可以安裝。此外，在安裝該應用程序時，無論您是否使用該應用程序，它都會使用該總存儲量。 PWA 的存儲處理方式不同。瀏覽器將根據您在 PWA 邏輯中定義的策略存儲您的資產。

<div style="background-color:#deeafd;padding:1rem;line-height:1.9;margin-top:1rem;color:#174ea6;margin-bottom:1rem">

The users are always in control, and they can delete the assets at any time. For PWAs, manual eviction happens via the browser's settings.
    
</div>

<div style="background-color:#deeafd;padding:1rem;line-height:1.9;margin-top:1rem;color:#174ea6;margin-bottom:1rem">

用戶始終處於控制之中，他們可以隨時刪除資產。對於 PWA，手動驅逐是通過瀏覽器的設置進行的。
    
</div>


Size limits depend on the browser. It's not as flexible as for platform-specific apps, but it's typically good enough for most web apps. You can find the specific limitations by browser in [this article](https://web.dev/storage-for-the-web/#how-much).

大小限制取決於瀏覽器。它不像特定於平台的應用程序那樣靈活，但對於大多數網絡應用程序來說通常已經足夠好了。您可以在本文中找到瀏覽器的具體限制。

Browsers can evict assets based on storage pressure, or after some weeks of inactivity, if the user is using your PWA in the browser. On some platforms, if the user installs your PWA, eviction won't happen. Where available, code can request persistent storage through an API to avoid that eviction.

如果用戶在瀏覽器中使用您的 PWA，瀏覽器可以根據存儲壓力或幾週不活動後驅逐資產。在某些平台上，如果用戶安裝了您的 PWA，則不會發生驅逐。在可用的情況下，代碼可以通過 API 請求持久存儲以避免這種驅逐。

<div style="background-color:#deeafd;padding:1rem;line-height:1.9;margin-top:1rem;color:#174ea6;margin-bottom:1rem">

If storage eviction happens for any reason and the user installed your PWA, the PWA will still work if you have a network connection. When you open that app again, the browser will start the service worker lifecycle again, loading your app from the network.
    
</div>

<div style="background-color:#deeafd;padding:1rem;line-height:1.9;margin-top:1rem;color:#174ea6;margin-bottom:1rem">

如果出於任何原因發生存儲逐出並且用戶安裝了你的 PWA，那麼如果你有網絡連接，PWA 仍然可以工作。當您再次打開該應用程序時，瀏覽器將再次啟動 Service Worker 生命週期，從網絡加載您的應用程序。
    
</div>

## Resources

* [Storage on the Web](https://web.dev/storage-for-the-web/)
* [MDN: Web Storage](https://developer.mozilla.org/zh-CN/docs/Web/API/Web_Storage_API)
* [MDN: IndexedDB](https://developer.mozilla.org/zh-CN/docs/Web/API/IndexedDB_API)