pwa缓存总结

1.sw.js

const cacheName = 'pwa-demo';

// 需要缓存的静态资源
const staticAssets = [
  './',
  './styles.css',
  './app.js'
];

self.addEventListener('install', async event => {
  const cache = await caches.open(cacheName);
  await cache.addAll(staticAssets);
});

self.addEventListener('fetch', event => {
  const req = event.request;
  const url = new URL(req.url);

  if (url.origin === location.origin) {
    event.respondWith(cacheFirst(req));
  } else {
    event.respondWith(networkFirst(req));
  }
});

async function cacheFirst(req) {
  const cachedResponse = await caches.match(req);
  return cachedResponse || fetch(req);
}

async function networkFirst(req) {
  const cache = await caches.open('dynamic-cache');

  try {
    const res = await fetch(req);
    cache.put(req, res.clone());
    return res;
  } catch (error) {
    return await cache.match(req);
  }
}

self.addEventListener('online', () => self.registration.showNotification('Network status: online'));

self.addEventListener('offline', () => self.registration.showNotification('Network status: offline'));

2.index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
<link rel="manifest" href="./manifest.json">
<link rel="stylesheet" href="styles.css"> </head> <body> <h1>PWA Demo</h1> <script> if ('serviceWorker' in navigator && 'Notification' in window) { window.addEventListener('load', function() { navigator.serviceWorker.register('/sw.js').then(() => { console.log('Service Worker Registered.'); checkNotificationPermission(); }, function(err) { console.log('Service Worker Registration Failed: ', err); }); window.addEventListener('online', showOnlineNotification); window.addEventListener('offline', showOfflineNotification); }); } function checkNotificationPermission() { if (Notification.permission === 'granted') { console.log('Notification permission granted.'); } else if (Notification.permission !== 'denied') { Notification.requestPermission().then(permission => { if (permission === 'granted') { console.log('Notification permission granted.'); } }); } } function showOnlineNotification() { if (Notification.permission === 'granted') { navigator.serviceWorker.getRegistration().then(reg => reg.showNotification('You are online')); } } function showOfflineNotification() { if (Notification.permission === 'granted') { navigator.serviceWorker.getRegistration().then(reg => reg.showNotification('You are offline')); } } </script> </body> </html>

3.manifest.json

{
  "short_name": "MyApp",
  "name": "My Progressive Web App",
  "icons": [
    {
      "src": "images/icon-192x192.png",
      "type": "image/png",
      "sizes": "192x192"
    },
    {
      "src": "images/icon-512x512.png",
      "type": "image/png",
      "sizes": "512x512"
    }
  ],
  "start_url": "/index.html",
  "background_color": "#3367D6",
  "display": "standalone",
  "scope": "/",
  "theme_color": "#3367D6"
}

 

posted @ 2023-09-01 09:46  卷叶小树  阅读(52)  评论(0编辑  收藏  举报