【问题标题】:Service Worker not working when hosted, but works on localhostService Worker 在托管时不工作,但在 localhost 上工作
【发布时间】:2021-04-11 22:14:40
【问题描述】:

我正在开发 PWA,但我遇到了 Service Worker 的问题,我不知道出了什么问题。

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

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

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

main.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


    【解决方案1】:
    const appShellFiles =  ['index.html',
        'help.html',
        'destinations.html',
        'contact.html',
        'js/main.js',
        'css/style.css',
        'sw.js'
    ];
    

    从您的 appShellFiles 中删除 sw.js

    【讨论】:

      猜你喜欢
      • 2021-04-17
      • 1970-01-01
      • 1970-01-01
      • 2018-11-25
      • 1970-01-01
      • 1970-01-01
      • 2018-07-21
      • 2020-03-21
      • 2023-03-26
      相关资源
      最近更新 更多