建立 PWA 漸進式網頁應用程式

做法

index.html 檔新增一些必要的標籤:

1
2
3
4
<meta name="theme-color" content="white">
<link rel="icon" href="images/icon.png">
<link rel="apple-touch-icon" href="images/icon.png">
<link rel="manifest" href="manifest.json">

在頁面載入時,註冊 service-worker.js 檔。

1
2
3
4
5
6
7
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('./service-worker.js');
});
}
</script>

新增 service-worker.js 檔,監聽相關事件,並且將必要的檔案快取起來,方便離線時使用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
self.addEventListener("install", (e) => {
e.waitUntil(
caches.open("store").then((cache) => {
return cache.addAll([
"/",
"/index.html",
]);
})
);
});

self.addEventListener("fetch", (e) => {
e.respondWith(
caches.match(e.request).then((response) => {
return response || fetch(e.request);
})
);
});

新增 manifest.json 檔,定義應用程式的相關設定:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
{
"name": "App Name",
"short_name": "App Short Name",
"start_url": "/index.html",
"display": "fullscreen",
"description": "App Description",
"icons": [
{
"src": "images/icon_64.png",
"sizes": "64x64",
"type": "image/png"
},
{
"src":"images/icon_192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src":"images/icon_512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"background_color": "grey",
"theme_color": "white"
}

除錯

打開 Chrome 開發者工具,點選 Lighthouse 頁籤,將 Progressive Web App 打勾後,點選「Generate report」,即可查看當前的網站是否符合 PWA 的規範。

參考資料