思涯谷

  • 首页
  • 探索
  • 标签
  • 关于
思涯谷 ©2025
京ICP备2022030312号GitHub User's stars

三步创建一个PWA应用

文章详细介绍了如何为“电车充电券规划计算器”创建和配置 `manifest.json`、`service-worker.js` 并更新 `index.html`,以实现离线访问和优化用户体验。

...
标签:前端教程
点赞(0)
返回顶部

相关内容

  • 根据背景获取文字颜色
  • 检查你的favicon配置是否正确
  • 斐讯R1配网和设置DLNA
  • Github Actions配置SSH部署
  • 面试笔记
01-17

留言

以「电车充电券规划计算器」为例。

1. 创建 ./manifest.json

{
  "name": "电车充电券规划计算器",
  "short_name": "充电券计算器",
  "description": "电车充电券规划计算器 - 思涯谷",
  "start_url": ".",
  "display": "standalone",
  "background_color": "#ffffff",
  "theme_color": "#4CAF50",
  "icons": [
    {
      "src": "./icon-192.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "./icon-512.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ]
}

2. 创建 ./service-worker.js

const CACHE_NAME = "e-power-plan-cache"
const urlsToCache = [
  ".",
  "./index.html",
  "./index.css",
  "./index.js",
  "./icon-192.png",
  "./icon-512.png",
  "/favicon.ico",
  "./manifest.json",
]

self.addEventListener("install", (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME).( {
       cache.(urlsToCache)
    })
  )
})

self.(,  {
   cacheWhitelist = []
  event.(
    caches.().( {
       .(
        cacheNames.( {
           (!cacheWhitelist.(cacheName)) {
             caches.(cacheName)
          }
        })
      )
    })
  )
})

self.(,  {
  event.(
    caches.(event.).( {
       (cachedResponse) {
         cachedResponse
      }
       (event.)
    })
  )
})
then
(cache) =>
return
addAll
addEventListener
"activate"
(event) =>
const
CACHE_NAME
waitUntil
keys
then
(cacheNames) =>
return
Promise
all
map
(cacheName) =>
if
includes
return
delete
addEventListener
"fetch"
(event) =>
respondWith
match
request
then
(cachedResponse) =>
if
return
return
fetch
request

3. 更新 ./index.html

在 HTML 文件中,做以下修改:

  1. 引入 manifest.json 文件

在 <head> 部分,添加对 manifest.json 的引用:

<link rel="manifest" href="./manifest.json" />
  1. 注册 Service Worker

紧接着 <body> 标签添加注册 Service Worker 的代码:

<body>
<script>
  if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
      navigator.serviceWorker
        .register('./service-worker.js')
        .then((registration) => {
          console.log('Service Worker registered with scope:', registration.scope);
        })
        .catch((error) => {
          console.log('Service Worker registration failed:', error);
        });
    });
  }
</script>
...
</body>

添加图标文件和nginx配置后,大功告成!

QQ截图20250117150846.png