对于未来的参考:
1/ 在应用根文件夹中创建一个服务工作者文件。
示例 sw.js:
let cacheName = "core" // Whatever name
// Pass all assets here
// This example use a folder named «/core» in the root folder
// It is mandatory to add an icon (Important for mobile users)
let filesToCache = [
"/",
"/index.html",
"/core/app.css",
"/core/main.js",
"/core/otherlib.js",
"/core/favicon.ico"
]
self.addEventListener("install", function(e) {
e.waitUntil(
caches.open(cacheName).then(function(cache) {
return cache.addAll(filesToCache)
})
)
})
self.addEventListener("fetch", function(e) {
e.respondWith(
caches.match(e.request).then(function(response) {
return response || fetch(e.request)
})
)
})
2/ 在应用的任意位置添加onload事件:
window.onload = () => {
"use strict";
if ("serviceWorker" in navigator && document.URL.split(":")[0] !== "file") {
navigator.serviceWorker.register("./sw.js");
}
}
3/ 在应用root文件夹中创建一个manifest.json文件。
{
"name": "APP",
"short_name": "App",
"lang": "en-US",
"start_url": "/index.html",
"display": "standalone"
}
4/ 测试示例。从 root 文件夹启动 Web 服务器:
php -S localhost:8090
访问http://localhost:8090 一次。
使用 Ctrl + c 停止 Web 服务器。
刷新http://localhost:8090,页面应该会响应。
开发时要关闭,去掉onload事件,在Firefox中
访问about:debugging#workers取消注册服务。
最新版本的 Firefox 直接在调试器中显示 application 选项卡。 about:debugging#workers 不再有效。
https://developer.mozilla.org/en-US/docs/Tools/Application/Service_workers
Source for more details
Manifest.json reference