如何指向 serviceworker.js 中的当前目录
How to point to current directory in serviceworker.js
我将 Service Worker 安装在暂存目录中
主网站在:https:example.com
分期开启:https:example.com/test/
Service Worker 路径:https:example.com/test/serviceworker.js
这是我注册 Service 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/)'
但这效率不高,会让我需要不同版本的 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 安装在暂存目录中
主网站在:https:example.com
分期开启:https:example.com/test/
Service Worker 路径:https:example.com/test/serviceworker.js
这是我注册 Service 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/)'
但这效率不高,会让我需要不同版本的 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/.