gpt4 book ai didi

service-worker - 如何指向 serviceworker.js 中的当前目录

转载 作者:行者123 更新时间:2023-12-04 06:38:24 24 4
gpt4 key购买 nike

我的 service worker 安装在一个临时目录中

主网站:https:example.com
分期开启:https:example.com/test/
Service Worker 路径:https:example.com/test/serviceworker.js
这是我注册服务 worker 的方式:

navigator.serviceWorker.register('https:example.com/test/serviceworker.js', {scope: '/test/'})
.then(registration => {
console.log(`Service Worker registered! Scope: ${registration.scope}`);
})

Service Worker 工作正常,并已安装。

我担心的是在 serviceworker.js 中我想使用 /自动指向当前目录的路径,在本例中为:/staging/

例如,当我想在临时站点中缓存主页时
/**
* Cache the homepage.
*/
workbox.routing.registerRoute('/', workbox.strategies.staleWhileRevalidate();

这里是缓存 https:example.com 不是 https:example.com/test/

我知道我可以简单地改变 registerRoute('/')registerRoute('/staging/)'
但这效率不高,并且会使我需要为 localhost、暂存和部署使用不同版本的 serviceworker。
我想知道在此处执行此操作的正确方法是什么,因此我可以将范围“/”设置为 serviceworker.js 所在的当前目录。
谢谢你。

最佳答案

好吧,我想我想出了如何以正确的方式做到这一点。

如何指向当前目录:只是 './' 而不是 '/'

/**
* Cache the homepage.
*/
workbox.routing.registerRoute('./', workbox.strategies.staleWhileRevalidate();

如何缓存当前路径中的文件和图像: './image/' 而不是 '/image/'
const urlsToCache = [
'./image/fallback.png',
'./offline/'
];

现在,同一个文件在本地和暂存时的工作方式相同。
这是一个新手错误,我需要更聪明:)

编辑:
我在 Google documentation (The Service Worker Lifecycle) 中找到了这个:

The default scope of a service worker registration is ./ relative to the script URL. This means if you register a service worker at //example.com/foo/bar.js it has a default scope of //example.com/foo/.

关于service-worker - 如何指向 serviceworker.js 中的当前目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54106395/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com