如何在停止后工作的服务工作者中加载外部脚本?

How to load external script in service worker that will work after stop?

我找不到此信息。如何使用importScripts在页面关闭后刷新一段时间后起作用?

我有这个代码:

self.addEventListener('install', function(evt) {
    self.skipWaiting();
    self.importScripts('https://cdn.jsdelivr.net/npm/idb-keyval/dist/umd.js');
});

我也试过:

self.addEventListener('install', function(event) {
    event.waitUntil(
        self.importScripts('https://cdn.jsdelivr.net/npm/idb-keyval/dist/umd.js')
    );
});
self.addEventListener('activate', (event) => {
    event.waitUntil(
        self.importScripts('https://cdn.jsdelivr.net/npm/idb-keyval/dist/umd.js')
    );
});

当我在几分钟后打开该站点时,出现有关缺少库的错误。

使用 importScripts 加载文件的正确方法是什么?我只想继续使用这个库。

我在任何地方都找不到这个信息,没有太多关于如何在 service worker 中使用外部库的例子。

它不一定是 importScripts 但这是我知道的在 Service Worker 中导入外部文件的唯一方法。我不确定你是否为此使用了 ES 模块。

编辑:

我也试过这个:

self.addEventListener('install', function(event) {
    self.skipWaiting();
    self.importScripts('https://cdn.jsdelivr.net/npm/idb-keyval/dist/umd.js');
    self.idb = idbKeyval;
});

self.addEventListener('activate', function(event) {
    if (!self.idb) {
        self.skipWaiting();
        self.importScripts('https://cdn.jsdelivr.net/npm/idb-keyval/dist/umd.js');
        self.idb = idbKeyval;
    }
});

我在 activate 事件中设置了断点,但它并没有像安装一样执行,我的变量也被删除了。

我正在通过停止开发工具中的服务工作者并刷新来进行测试。每次都出现关于缺少 idb.

的错误

我也试过在 service worker 中使用本地 let 变量,得到了相同的结果 idb is undefined, after service worker was stopped.

EDIT2:

我已经 asked the author on GitHub,因为这可能是图书馆的问题。

What is the proper way to load a file with importScripts that will work? I just want to keep using this library.

您通常会在服务工作者的全局范围内使用 importScripts,在任何事件回调之外:

importScripts('https://cdn.jsdelivr.net/npm/idb-keyval/dist/umd.js');

self.addEventListener('install', function (evt) {
  // your install handler
  // `self.idbKeyval` should be available here, as well as anywhere else
});