首页 > 解决方案 > Service Worker 在托管时不工作,但在 localhost 上工作

问题描述

我正在开发 PWA,但我遇到了服务人员的问题,我不知道出了什么问题。

因此,当我在 localhost 上运行灯塔审核时,它通过了除 HTTPS 之外的所有标准。您可以在下面查看它; 在此处输入图像描述

但是,当我将代码发布到我的 github 页面并在那里运行相同的审核时,服务工作者永远不会被激活。它给了我错误。当我在线运行审核时,状态变为“冗余”。链接:https ://ibr4h1m.github.io/MAD5/index.html

下面我将展示代码,这与我上面提到的网站上的代码完全相同。

主.js:

//Simple ServiceWorker
if('serviceWorker' in navigator) {
  navigator.serviceWorker.register('sw.js');
};

sw.js

const cacheName = 'tourguide-site';
const appShellFiles =  ['index.html',
    'help.html',
    'destinations.html',
    'contact.html',
    'js/main.js',
    'css/style.css',
    'sw.js'
];


self.addEventListener('install', (e) => {
  console.log('[Service Worker] Install');
  e.waitUntil((async () => {
    const cache = await caches.open(cacheName);
    console.log('[Service Worker] Caching all: app shell and content');
    await cache.addAll(appShellFiles);
  })());
});


// Simple Activate since the other one is BS

self.addEventListener('activate', function () {
  console.log('SW Activated');
});

self.addEventListener('fetch', (e) => {
  e.respondWith((async () => {
    const r = await caches.match(e.request);
    console.log(`[Service Worker] Fetching resource: ${e.request.url}`);
    if (r) { return r; }
    const response = await fetch(e.request);
    const cache = await caches.open(cacheName);
    console.log(`[Service Worker] Caching new resource: ${e.request.url}`);
    cache.put(e.request, response.clone());
    return response;
  })());
});

在线审核: 在此处输入图像描述 在此处输入图像描述 在此处输入图像描述

标签: progressive-web-apps

解决方案


const appShellFiles =  ['index.html',
    'help.html',
    'destinations.html',
    'contact.html',
    'js/main.js',
    'css/style.css',
    'sw.js'
];

sw.js从您的 appShellFiles 中删除


推荐阅读