Service Worker 'Hello World' 示例
Service Worker 'Hello World' example
我正在学习服务工作者,因为我有一个用例来创建一个获取监听器,它将传回任意二进制响应。
我不知道从哪里开始。我在网上看到的例子都是关于发出服务器请求、在服务工作者中缓存并将其传回的。我真正想做的只是传回我自己的响应,而不是向服务器查询并缓存它!
我正在寻找的是,作为开始,假设用户在浏览器中输入,一旦服务工作人员处于活动状态,就会说一些事情,(或使用 fetch api 获得以下内容 url)
http:///myapp/helloworld
将在浏览器中显示 'Helloworld'。 Service Worker 将类似于以下内容。但是我不知道它是如何工作的。
self.addEventListener('fetch', event => {
// compare end of url with /helloworld
// if match, respond with 'helloword', otherwise fetch the response from the server
});
这只是一个非常简短、广泛的概述,说明我将如何解决这个问题。
首先,我会遵循这样的指南:
https://css-tricks.com/add-a-service-worker-to-your-site/
// Listen for request events
self.addEventListener('fetch', function (event) {
// Get the request
let request = event.request;
...
}
然后您将使用这段代码作为您想要执行的操作的指南:
event.respondWith(
fetch(request).then(function (response) {
return response;
}).catch(function (error) {
return caches.match(request).then(function (response) {
return response;
});
})
);
经过一些修改。
首先,您需要检查它是否是正常的 non-/helloworld 类型的请求,如果是,请执行以下操作:
if (normalRequest) {
event.respondWith(
fetch(request).then(function (response) {
return response;
});
} else {
... TODO
}
并且在 TODO 部分,您将执行 helloworld
代码 - 我不清楚您想要用它做什么,所以我不能真正详细说明。但这是我会使用的整体结构。
我正在学习服务工作者,因为我有一个用例来创建一个获取监听器,它将传回任意二进制响应。
我不知道从哪里开始。我在网上看到的例子都是关于发出服务器请求、在服务工作者中缓存并将其传回的。我真正想做的只是传回我自己的响应,而不是向服务器查询并缓存它!
我正在寻找的是,作为开始,假设用户在浏览器中输入,一旦服务工作人员处于活动状态,就会说一些事情,(或使用 fetch api 获得以下内容 url)
http:///myapp/helloworld
将在浏览器中显示 'Helloworld'。 Service Worker 将类似于以下内容。但是我不知道它是如何工作的。
self.addEventListener('fetch', event => {
// compare end of url with /helloworld
// if match, respond with 'helloword', otherwise fetch the response from the server
});
这只是一个非常简短、广泛的概述,说明我将如何解决这个问题。
首先,我会遵循这样的指南:
https://css-tricks.com/add-a-service-worker-to-your-site/
// Listen for request events
self.addEventListener('fetch', function (event) {
// Get the request
let request = event.request;
...
}
然后您将使用这段代码作为您想要执行的操作的指南:
event.respondWith(
fetch(request).then(function (response) {
return response;
}).catch(function (error) {
return caches.match(request).then(function (response) {
return response;
});
})
);
经过一些修改。
首先,您需要检查它是否是正常的 non-/helloworld 类型的请求,如果是,请执行以下操作:
if (normalRequest) {
event.respondWith(
fetch(request).then(function (response) {
return response;
});
} else {
... TODO
}
并且在 TODO 部分,您将执行 helloworld
代码 - 我不清楚您想要用它做什么,所以我不能真正详细说明。但这是我会使用的整体结构。