447 字
2 分钟
PWA——渐进式Web应用

创建清单文件#

  1. 在您的网站根目录下创建一个名为”manifest.json”的文件。这个文件将包含网站的元数据和图标信息,用于在浏览器中显示PWA。 内容如下:

    {
    "lang": "en-us",
    "name": "逆行时光",
    "short_name": "逆行时光",
    "description": "个人主页",
    "start_url": "/",
    "background_color": "#fff",
    "theme_color": "#fff",
    "orientation": "any",
    "display": "standalone",
    "icons": [
    {
    "src": "/icon.png",
    "sizes": "512x512"
    }
    ]
    }

    常用键名解释:

    • `name` :应用的名称,将显示在浏览器的应用商店或添加应用对话框中。
    • short_name: 应用的简称,用于在应用图标下方显示的简短名称。
    • theme_color: 应用的主题颜色,用于定义浏览器标签和地址栏的颜色。
    • background_color: 应用的背景颜色,通常用于定义应用的启动屏幕和页面的背景。
    • display: 定义应用的显示模式,可以是standalone(独立模式)、fullscreen(全屏模式)等。
    • icons: 定义应用图标的数组,每个图标指定了图片的路径、类型和尺寸。
  2. 在首页head标签引入文件

创建service worker(不想使用缓存可以不创建)#

  1. 根目录新建文件”sw.js”,例子如下:

    const CACHE_NAME = 逆行时光;
    // Use the install event to pre-cache all initial resources.
    self.addEventListener('install', event => {
    event.waitUntil((async () => {
    const cache = await caches.open(CACHE_NAME);
    cache.addAll([
    '/',
    '/index.js',
    '/index.css'
    ]);
    })());
    });
    self.addEventListener('fetch', event => {
    event.respondWith((async () => {
    const cache = await caches.open(CACHE_NAME);
    // Get the resource from the cache.
    const cachedResponse = await cache.match(event.request);
    if (cachedResponse) {
    return cachedResponse;
    } else {
    try {
    // If the resource was not in the cache, try the network.
    const fetchResponse = await fetch(event.request);
    // Save the resource in the cache and return it.
    cache.put(event.request, fetchResponse.clone());
    return fetchResponse;
    } catch (e) {
    // The network failed.
    }
    }
    })());
    });
  2. 在首页body标签后引入脚本注册

    if('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/sw.js', { scope: '/' });
    }

    在pc端edge浏览器安装或者添加到手机即可#

PWA——渐进式Web应用
https://blog.160621.xyz/posts/pwa渐进式web应用/
作者
逆行时光
发布于
2023-03-09
许可协议
CC BY-NC-SA 4.0